﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using WP.Commons;
using WP.DB;
using WP.Modules;
using WP.Controls;
using WP.Controls.GridColumn;

using WP.RM.BusinessRule;
using WP.RM.BusinessLogical;
using WP.RM.DataAccess;

namespace WP.RM.Form
{
    public partial class frmRMProductBOMMtn : BaseMtn 
    {
        public frmRMProductBOMMtn()
        {
            InitializeComponent();
            LoadAllControl(new ArrayList(this.Controls));
            this.MtnTabControl = this.tbcMain;
            this.DesignTabsName = "tbpGeneral";
            tbcMain.DrawMode = TabDrawMode.OwnerDrawFixed;
            this.MinimumSize = this.Size;
        }
        public void ShowFromQry( string strRecID)
        {
            this.Show();
            this.Text = "产成品BOM单维护";
            this.RecID = Convert.ToInt64(strRecID );

        }
        private void FillTree()
        {
            DBAccess dbcon = new DBAccess(false, false);
            string strSQL = "select TypeId,TypeName,RecID from RMProductFirstType order by TypeId";
            DataTable dtItem = dbcon.GetDataTable(strSQL);
            foreach (DataRow drType in dtItem.Rows)
            {
                TreeNode tvNode = new TreeNode(CvtFunc.ToString(drType["TypeId"]) + "-" + CvtFunc.ToString(drType["TypeName"]));
                this.tvTree.Nodes.Add(tvNode);
                int intRow = 0;
                strSQL = "select TypeId,TypeName from RMProductSecondType where parentid='" + CvtFunc.ToString(drType["RecID"]) + "'";
                DataTable dtDtl = dbcon.GetDataTable(strSQL);
                foreach (DataRow drDtl in dtDtl.Rows)
                {
                    tvNode.Nodes.Add(CvtFunc.ToString(drDtl["TypeId"]) + "-" + CvtFunc.ToString(drDtl["TypeName"]));
                }
            }
            dbcon.CloseCon();
        }
        #region Define Variable
        private bool mblnSettingStatus = false;
        private bool[] mDtlColumnReadOnlyArray;
        private bool[] mDtlColumnReadOnlyArray_LabourCost;
        private bool m_bCanTrigerCellValueChangedEven = false;
        private bool m_bCanTrigerCellValueChangedEven_LabourCost = false;
        private bool m_bSettingStatus = false;
        private bool m_bDtlChanged = false;
        private bool m_bDtlChanged_LabourCost = false;
        private bool m_bCanTrigerCellValueChangedEven_SemiProduct = false;
        private string mstrWhereCondition = "";
        private frmWKParameter frmParameter = null; 
        private System.Windows.Forms.DataGridView.HitTestInfo mhtiDtl = null;
        private DBAccess mdbcon = new DBAccess(false, false);
        
        private enum DtlCol
        {
            RowSeqNo = 0,
            SeqNo,
            ProductFItemID,
            ProductName,
            TechnicsName,
            WKID,
            WKName,
            WKRemark,
            IsKeyWK,
            IsInputWK,
            CategoryID,
            CategoryName,
            SetID,
            SetName,
            FItemID,
            ItemNo,
            ItemName,
            SupNo,
            SupName,
            Price,
            PriceUnit,
            /// <summary>
            /// 计划基本单价，主要用于半成品的计算
            /// </summary>
            PlanTreatCost,
            Qty,         //定额数量
            WastageRate, //损耗率 
            QtyWastage,  //损耗数量
            DetailCost,  //定额成本
            LabourCost,  //人工成本
            TotalCost,   //总成本     
            RecID,
            ValueChanged,
            DelButton
        }

        private enum LabourCostCol
        {
            RowSeqNo = 0,
            BOMSeqNo,
            SeqNo,
            WKID,
            WKName,
            /// <summary>
            /// 工价类别
            /// </summary>
            WKPriceType,
            WKRemark,
            IsKeyWK,
            WKOutName,
            CategoryID,
            CategoryName,
            SetID,
            SetName,
            ProductFItemID,
            ProductName,
            TechnicsName,
            FItemID,
            /// <summary>
            /// 主要是用来计算这个工序要做的工作总量
            /// </summary>
            ItemNo,      
            ItemName,
            CalUnit,
            CutType,
            /// <summary>
            /// 总数量
            /// </summary>
            WorkQty,
            /// <summary>
            /// 总加工计量数量( = WorkQty/ CutType )
            /// </summary>
            TotalQty,    
            /// <summary>
            /// 10小时额定产量
            /// </summary>
            StandardQty, 
            /// <summary>
            /// 预计用工时间
            /// </summary>
            UsedHours,   
            /// <summary>
            /// 固定工资
            /// </summary>
            StandardWage, 
            /// <summary>
            /// 26天标准工资
            /// </summary>
            StandardWage26, 
            /// <summary>
            /// 记件工价
            /// </summary>
            UnitCost,
            /// <summary>
            /// 计件工资
            /// </summary>           
            TotUnitCost,
            /// <summary>
            /// 人工成本 = 总工价*数量 //总工价来自于工时费用标准 TotUnitCost
            /// </summary>
            DtlLaborTotCost,
            /// <summary>
            /// 工时费用标准
            /// </summary>
            WorkCost,   
            /// <summary>
            /// 工时费用
            /// </summary>
            TotWorkCost, 
            /// <summary>
            /// 备注
            /// </summary>
            Remark,
            RecID,
            ValueChanged,
            DelButton
        }

        #endregion

        #region ***Form Events

        private void frmRMProductBOMMtn_Load(object sender, EventArgs e)
        {
            this.TableName = "rmProductBOMHdr";
            frmParameter = new frmWKParameter(frmWKParameter.FromType.Product);
            pnlParameter.Enabled = true ;
            //dgList.ColumnWidth = "0,70,180,100,40,20,120,90,130";
            dgList.ConnectionString = DBAccess.ConnectionDBString;
            dgList.TableName = this.TableName;
            dgList.ColumnWidth = DataFunctions.GetGridColumnWidthString(this.Name, this.CurrentMenuInfo.iParameter, SysVar.UserName, this.Name + "." + this.dgList.Name);
            string strSql = WP.Commons.BaseFunctions.GetLookUpSQL(this.TableName, this.CurrentMenuInfo.iParameter);
            dgList.Sql = strSql;
            this.formStatus = FormStatus.Query;
            InitGridDtl();
            FillLookUpInfo();
            ShowOverViewGrid((this.CurrentMenuInfo.strOverViewCondition != "" && this.CurrentMenuInfo.strOverViewCondition != null ? " Where " : "") + this.CurrentMenuInfo.strOverViewCondition);

            frmParameter.TopMost = true;
            frmParameter.TopLevel = false;
            frmParameter.Dock = DockStyle.Fill;
            frmParameter.FormBorderStyle = FormBorderStyle.None;
            frmParameter.Show();
            pnlParameter.Controls.Add(frmParameter);

            FillTree();
        }

        private bool  InitBOMHdr()
        {         
            DBAccess dbcon = new DBAccess(false, false);
            RMProductBOMHdrBRL rmBRL = new RMProductBOMHdrBRL();
            try
            {
                if (txtCategoryName.Text == "" || txtSetName.Text == "" || txtProductName.Text == "") return false ;
                
                string strSQL = "select * from rmProductBOMHdr where CategoryID='{0}' and SetID='{1}' and ProductFItemID='{2}' and TechnicsName='{3}'";
                strSQL = string.Format(strSQL, txtCategoryID.Text, txtSetID.Text, txtProductFItemID.Text,txtTechnicsName.Text);
                DataRow drRow = dbcon.GetDataFirstRow(strSQL);
                #region 检查 【类别系列BOM】是不是已被审核
                strSQL = " select * from rmCategorySetBOMHdr A where A.Approval=1";
                strSQL += " and A.CategoryID='{0}' and A.SetID='{1}'  ";
                strSQL = string.Format(strSQL, txtCategoryID.Text, txtSetID.Text);
                DataRow drCheck = dbcon.GetDataFirstRow(strSQL);
                if (drCheck == null)
                {
                    if (MessageBox.Show("没有被审核 【类别系列BOM】,是否继续？", "", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == System.Windows.Forms.DialogResult.No)
                    {
                        return false;
                    }
                    else
                    {
                        return true;
                    }
                }
                #endregion

                if (!UpdateData()) return false;
                if (drRow == null)
                {
                    this.Cursor = Cursors.WaitCursor; 
                    dbcon.BeginTran();
                    string strProductFItemID = txtProductFItemID.Text;
                    if (rmBRL.InitProductBOMFromCategorySet(dbcon, strProductFItemID, txtCategoryID.Text, txtSetID.Text,txtTechnicsName.Text))
                        dbcon.CommitTran();
                    else
                        dbcon.RollbackTran();                    
                }
            }
            catch (Exception ex)
            {
                this.Cursor = Cursors.Default;
                dbcon.RollbackTran(); 
            }
            this.Cursor = Cursors.Default;
            FillDtl(txtCategoryID.Text, txtSetID.Text, txtProductFItemID.Text, txtTechnicsName.Text);
            FillDtl_LabourCost(txtCategoryID.Text, txtSetID.Text, txtProductFItemID.Text, txtTechnicsName.Text);
            dbcon.CloseCon();
            return true;
        }

        private void ShowOverViewGrid()
        {
            ShowOverViewGrid("");
        }

        private void ShowOverViewGrid(string strWhereCondition)
        {
            string strSql = "";
            if (dgList.Sql.Trim() == "")
                strSql = WP.Commons.BaseFunctions.GetLookUpSQL(this.TableName, this.CurrentMenuInfo.iParameter);
            else
                strSql = dgList.Sql;

            if (strWhereCondition != "")
            {
                string strOrderBy = BaseFunctions.GetSqlParts(strSql, SqlOption.SqlPartOrderBy);
                strSql = BaseFunctions.GetSqlParts(strSql, SqlOption.SqlPartMain) + " " + strWhereCondition;
                strSql += strOrderBy;
            }
            string strWhere = BaseFunctions.GetSqlParts(strSql, SqlOption.SqlPartWhere);
            mstrWhereCondition = strWhere;
            this.dgList.Sql = strSql;
        }
        private void frmRMProductBOMMtn_FormClosing(object sender, FormClosingEventArgs e)
        {
            DataFunctions.SetGridColumnWidthString(this.Name, this.CurrentMenuInfo.iParameter, SysVar.UserName, this.dgList);
            DataFunctions.SetGridColumnWidthString(this.Name, this.CurrentMenuInfo.iParameter, SysVar.UserName, this.dgvBOM);
            DataFunctions.SetGridColumnWidthString(this.Name, this.CurrentMenuInfo.iParameter, SysVar.UserName, this.dgvLabourCost);

            DataFunctions.SetGridColumnWidthString(this.Name, this.CurrentMenuInfo.iParameter, SysVar.UserName, this.dgvSemiBOM );
            DataFunctions.SetGridColumnWidthString(this.Name, this.CurrentMenuInfo.iParameter, SysVar.UserName, this.dgvSemiProduct );
            DataFunctions.SetGridColumnWidthString(this.Name, this.CurrentMenuInfo.iParameter, SysVar.UserName, this.dgvSubSemiProduct);
            DataFunctions.SetGridColumnWidthString(this.Name, this.CurrentMenuInfo.iParameter, SysVar.UserName, this.dgvSemiSubCost);
        }
        private void btnUpdate_Click(object sender, EventArgs e)
        {
            if (this.formStatus == FormStatus.AddNew && tbcMain.SelectedTab == tbpGeneral)
            {
                if (!InitBOMHdr()) return ;
            }
             if (!this.UpdateData()) return;
            base.SetStatusAfterUpdate();
        }
        private void btnNew_Click(object sender, EventArgs e)
        {
            if (this.ConfirmChange())
            {
                if (!this.UpdateData()) return;
            }
            this.formStatus = FormStatus.AddNew;
        }
        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (!this.DeleteData()) return;


        }
        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.formStatus = FormStatus.Delete;
        }
        private void btnExit_Click(object sender, EventArgs e)
        {
            if (this.formStatus == FormStatus.AddNew || this.formStatus == FormStatus.Update)
            {
                if (this.ConfirmChange())
                {
                    if (MessageBox.Show(SysVar.SaveChangeTitle, SysVar.WarnTitle, MessageBoxButtons.YesNo) == DialogResult.Yes)
                    {
                        if (!this.UpdateData()) return;
                    }
                }
            }
            this.ExitingStatus = true;
            this.Close();
        }
        private void btnHelp_Click(object sender, EventArgs e)
        {
            base.OnHelp();
        }
        private void btnToExcel_Click(object sender, EventArgs e)
        {
            if (this.tbcMain.SelectedTab == this.tbpOverview)
                base.ExportToExcel(dgList);
            else
            {
                string strSQL = "";
                strSQL = "select * from rmProduct where recid ='" + this.m_lRecId + "'";
                DataRow drHdr = mdbcon.GetDataFirstRow(strSQL);
                if (drHdr == null) return;

                BOMToExcel.ToExcel_BOM(mdbcon, BOMToExcel.BOMType.ProductBOM, drHdr);
            }
        }
        private void btnNext_Click(object sender, EventArgs e)
        {
            Nevigate(this.dgList, NavigateOrient.Next);
        }
        private void btnPrev_Click(object sender, EventArgs e)
        {
            Nevigate(this.dgList, NavigateOrient.Prev);
        }
        private void btnTop_Click(object sender, EventArgs e)
        {
            Nevigate(this.dgList, NavigateOrient.Top);
        }
        private void btnBottom_Click(object sender, EventArgs e)
        {
            Nevigate(this.dgList, NavigateOrient.Bottom);
        }
        public override void SetNavigatorBarTooltip()
        {
            if (this.RecID <= 0)
            {
                this.btnBottom.ToolTipText ="定位到末页";
                this.btnTop.ToolTipText = "定位到首页";
                this.btnNext.ToolTipText ="定位到下一页";
                this.btnPrev.ToolTipText ="定位到前一页";
            }
            else
            {
                this.btnBottom.ToolTipText ="定位到末记录" ;
                this.btnTop.ToolTipText = "定位到首记录" ;
                this.btnNext.ToolTipText = "定位到下一条记录" ;
                this.btnPrev.ToolTipText = "定位到上一条记录" ;
            }
        }

        private void dgList_DefineColumn(object sender, EventArgs e)
        {
            base.SelectListViewField(dgList);
        }
        private void dgList_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter && dgList.CurrentRow != null && this.tbcMain.SelectedTab == tbpOverview )
            {
                this.RecID = Convert.ToInt64(dgList.RecID);
            }
        }
        private void dgList_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (dgList.CurrentRow != null && BaseFunctions.IsDataGridCell(this.dgList, e))
            {
                this.RecID = Convert.ToInt64(dgList.RecID);
            }
        }

        protected override void Field_Leave(object sender, System.EventArgs e)
        {
            base.Field_Leave(sender, e);
            Control con = sender as Control;
            if (con == null) return;

            //below is some speci field , need do some speci work
            if (con.Name == txtCategoryName.Name)
            {
            }
            else if (con.Name == txtTechnicsName.Name)
            {
                if (this.formStatus == FormStatus.AddNew)
                {
                    InitBOMHdr(); 
                }
            }
        }
        protected override void Field_Change(object sender, EventArgs e)
        {
            base.Field_Change(sender, e);
            if (this.formStatus == FormStatus.Delete) return;
            Control con = sender as Control;
            if (con == null) return;

            if (con.Name == txtProductFItemID.Name)
            {
                txtCategoryID.Text = DataFunctions.GetFieldValue ("rmProduct","CategoryID","ProductFItemID='"+ txtProductFItemID.Text +"'");
                txtSetID.Text = DataFunctions.GetFieldValue ("rmProduct","SetID","ProductFItemID='"+ txtProductFItemID.Text +"'");
            }
            if (this.formStatus == FormStatus.Update)
            {
                if (con.Name.StartsWith("utrapproval"))
                {
                    SetControlByApproLevel();
                    SetApprovalControlEnable();
                    ApprovalCategoryBOM(con);
                }
            }
        }
        protected override void Field_KeyPress(object sender, KeyPressEventArgs e)
        {
            base.Field_KeyPress(sender, e);
        }
        protected override bool ProcessCmdKey(ref System.Windows.Forms.Message msg, System.Windows.Forms.Keys keyData) //激活回车键
        {
            int WM_KEYDOWN = 256;
            int WM_SYSKEYDOWN = 260;
            if (!(msg.Msg == WM_KEYDOWN | msg.Msg == WM_SYSKEYDOWN))
            {
                return false;
            }

            bool blnRet = false;
            if (BaseFunctions.TrigerKeyEventByControl(this.ActiveControl, this.dgvBOM.Name))
            {
                blnRet = dgvBOM_KeyDownEvent(keyData);
            }
            else if (BaseFunctions.TrigerKeyEventByControl(this.ActiveControl, this.dgvLabourCost.Name))
            {
                blnRet = dgvLabourCost_KeyDownEvent(keyData);
            }
            if (!blnRet)
            {
                return base.ProcessCmdKey(ref msg, keyData);
            }
            return blnRet;
        }
        private void tbcMain_Selecting(object sender, TabControlCancelEventArgs e)
        {
            FuntoolStripMenuItem.Enabled = true;
            if ((this.formStatus == FormStatus.Query || this.formStatus == FormStatus.Delete) &&
                this.dgList.Rows.Count == 0 && e.TabPageIndex > 0)
            {
                e.Cancel = true;
                return;
            }

            if (e.TabPageIndex == 0)
            {
                if (this.formStatus == FormStatus.AddNew || this.formStatus == FormStatus.Update)
                {
                    if (this.ConfirmChange())
                    {
                        if (MessageBox.Show(SysVar.SaveChangeTitle, SysVar.WarnTitle, MessageBoxButtons.YesNo) == DialogResult.Yes)
                        {
                            if (!this.UpdateData())
                            {
                                if (m_bTabPageNeedCancel)
                                    e.Cancel = true;

                                m_bTabPageNeedCancel = true;
                                return;
                            }
                        }
                    }
                    this.formStatus = FormStatus.Delete;
                }
                else if (this.formStatus == FormStatus.Query)
                {
                    this.formStatus = FormStatus.Delete;
                }
                this.dgList.RefreshData();
                this.dgList.Focus();
            }
            else if (e.TabPageIndex != 0 && this.formStatus != FormStatus.AddNew)
            {
                if (this.RecID == -1)
                    this.RecID = Convert.ToInt64(dgList.RecID);

                if (e.TabPage == tbpOtherCost && (this.dgvBOM.CurrentRow == null  || CvtFunc.ToString ( this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKID].Value )==""))
                {
                    this.tbcMain.SelectedTab = tbpBOM;
                }
            }

            else if (e.TabPageIndex == 2 && this.formStatus == FormStatus.AddNew)
            {
                if (this.formStatus == FormStatus.AddNew)
                {
                    e.Cancel = !InitBOMHdr();
                }
            }
            else if ((e.TabPage == tbpBOM || e.TabPage == tbpOtherCost) && this.formStatus == FormStatus.AddNew)
            {
                e.Cancel = !InitBOMHdr();
            }
            if (e.TabPage == tbpGeneral && this.formStatus == FormStatus.Update && this.tbcMain.SelectedTab == tbpBOM)
            {
                string strSQL = "";
                string strRecID="";
                RMProductBOMHdrDAL rmDAL = new RMProductBOMHdrDAL();
                DataGridViewRow drvRow =null ; 
                if (this.dgvBOM.CurrentRow != null)
                {
                    strRecID = CvtFunc.ToString ( this.dgvBOM.CurrentRow.Cells[(int)DtlCol.RecID].Value) ;
                    drvRow = this.dgvBOM.CurrentRow;
                    if (CvtFunc.ToInt(strRecID) > 0)
                    {
                        Update_Detail(drvRow);
                    }
                }
                else if ( this.dgvLabourCost.CurrentRow !=null )
                {
                    strRecID = CvtFunc.ToString(this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.RecID].Value);
                    drvRow = this.dgvLabourCost.CurrentRow;
                    if (CvtFunc.ToInt(strRecID) > 0)
                    {
                        Update_Detail_LabourCost (drvRow);
                    }
                }
               
               FillHdrData(txtCategoryID.Text , txtSetID.Text , txtProductFItemID.Text , txtTechnicsName.Text);
            }
            if (e.TabPage == tbpOtherCost)
            {
                FuntoolStripMenuItem.Enabled = false;
            }
        }
        private void tbcMain_DrawItem(object sender, DrawItemEventArgs e)
        {
            BaseFunctions.TabControl_DrawItem(sender, e, true);
        }
        private void FileMenu_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem mnuItem = sender as ToolStripMenuItem;
            if (mnuItem != null)
            {
                switch (mnuItem.Name)
                {
                    case "newToolStripMenuItem":
                        btnNew_Click(sender, e);
                        break;
                    case "cancelToolStripMenuItem":
                        btnCancel_Click(sender, e);
                        break;
                    case "deleteToolStripMenuItem":
                        btnDelete_Click(sender, e);
                        break;
                    case "saveToolStripMenuItem":
                        btnUpdate_Click(sender, e);
                        break;
                    case "exitToolStripMenuItem":
                        btnExit_Click(sender, e);
                        break;
                }
            }
        }

        #endregion Form Events***

        #region ***Form Functions

        public override bool UpdateData()
        {
            bool bUpdateResult = true;
            string strErrMsg = "";
            if (this.formStatus == FormStatus.Query) return true ;
            if (this.dgvBOM.CurrentRow != null)
            {
                this.dgvBOM.EndEdit();
                if (!CheckDtlRow(ref strErrMsg))
                {
                    MsgBoxEx.Show(strErrMsg, SysVar.WarnTitle);
                    return false;
                }
                else
                {
                    if ( CvtFunc.ToInt ( this.dgvBOM.CurrentRow.Cells[(int)DtlCol.ValueChanged].Value)>0)
                    {
                        Update_Detail(this.dgvBOM.CurrentRow);
                    }
                }
            }
            if (this.dgvLabourCost.CurrentRow != null)
            {
                this.dgvLabourCost.EndEdit();
                if (!CheckDtlRow_LabourCost(ref strErrMsg))
                {
                    if (CvtFunc.ToString(this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKName].Value) != "")
                    {
                        MsgBoxEx.Show(strErrMsg, SysVar.WarnTitle);
                        return false;
                    }
                }
                else
                {
                    if (CvtFunc.ToInt(this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.ValueChanged].Value) > 0)
                    {
                        Update_Detail_LabourCost(this.dgvLabourCost.CurrentRow);
                    }
                }
            }
            if (base.ConfirmChange())
            {
                bUpdateResult = base.UpdateData();
            }
            return bUpdateResult;
        }
        public override bool ConfirmChange()
        {
            return (base.ConfirmChange());
        }
        protected override bool FieldCheck(string strFieldValue, string strFieldName, ref string strErrPrompt)
        {

            strErrPrompt = string.Empty;
            DBAccess dBAccess = new DBAccess(false, false);
            DataRow dr = base.GetCurrentMtnDataRow();

            RM.BusinessRule.RMProductBOMHdrBRL mBRL = new WP.RM.BusinessRule.RMProductBOMHdrBRL();
            bool bCheckResult = mBRL.FieldCheck(dBAccess, dr, strFieldName, ref strErrPrompt, this.formStatus);
            dBAccess.CloseCon();
            return bCheckResult;
        }

        protected override string GetLookUpSQL(string strTableName, string strLookUpControlName)
        {
            string strSql = string.Empty;
            strSql = base.GetLookUpSQL(strTableName, strLookUpControlName);
            string strMainSQL = BaseFunctions.GetSqlParts(strSql, SqlOption.SqlPartMain);
            string strWhere = BaseFunctions.GetSqlParts(strSql, SqlOption.SqlPartWhere);
            string strOrderBy = BaseFunctions.GetSqlParts(strSql, SqlOption.SqlPartOrderBy);
            if (strLookUpControlName == this.ubtCategoryName.Name)
            {
                strSql = base.GetLookUpSQL(strTableName, strLookUpControlName);

            }
            else if (strLookUpControlName == this.ubtSetName.Name)
            {

            }
            else if (strLookUpControlName == this.ubtProductName.Name)
            {
                if (strWhere == "")
                {
                    strWhere = " where 1=1 ";
                }
                if (txtCategoryName.Text != "")
                {
                    strWhere += " and CategoryName='" + txtCategoryName.Text + "' ";
                }
                if (txtSetName.Text != "")
                {
                    strWhere += " and SetName='" + txtSetName.Text + "'";
                }
                else
                {
                    return strSql;
                }
            }
            return base.GetLookUpSQL(strTableName, strLookUpControlName);
        }

        protected override void ubtLookUp_Click(object sender, EventArgs e)
        {
           
            Control con = sender as Control;
            if (con.Name == ubtProductName.Name)
            {
                string strSQL = BaseFunctions.GetLookUpSQL("rmProduct");
                frmLookUpProduct frmlookup = new frmLookUpProduct(strSQL, "产成品选择", con.Text , "ProductName");
                frmlookup.ShowDialog();
                if (frmlookup.HaveReturnValue)
                {
                    txtProductName.Text =frmlookup.GetReturnValue("ProductName");
                    txtProductID.Text   =frmlookup.GetReturnValue("ProductID");
                    txtProductFItemID.Text   =frmlookup.GetReturnValue("ProductFItemID");
                    txtProductType.Text  =frmlookup.GetReturnValue("ProductType"); 

                    txtCategoryName.Text =  DataFunctions.GetFieldValue("rmProduct", "CategoryName", "ProductFItemID='" + txtProductFItemID.Text + "'");
                    txtSetName.Text =  DataFunctions.GetFieldValue("rmProduct", "SetName", "ProductFItemID='" + txtProductFItemID.Text + "'");
                    txtCategoryID.Text =  DataFunctions.GetFieldValue("rmProduct", "CategoryID", "ProductFItemID='" + txtProductFItemID.Text + "'");
                    txtSetID.Text =   DataFunctions.GetFieldValue("rmProduct", "SetID", "ProductFItemID='" + txtProductFItemID.Text + "'");
                }
                frmlookup.Close(); 
            }
            else
            {
                base.ubtLookUp_Click(sender, e);
            }
        }
        public override void SetButtonStatus()
        {
            switch (this.formStatus)
            {
                case FormStatus.AddNew:
                    BaseFunctions.ControlEnabled(this.toolStrip, false);
                    this.btnUpdate.Enabled = true;
                    this.btnDelete.Enabled = false;
                    this.btnNew.Enabled = true;
                    this.btnCancel.Enabled = true;
                    this.btnTallyCalculate.Enabled = false;
                    this.FuntoolStripMenuItem.Enabled =  false ;
                    this.btnCopyTo.Enabled = false;
                    break;
                case FormStatus.Delete:
                    BaseFunctions.ControlEnabled(this.toolStrip, false);
                    this.btnUpdate.Enabled = false;
                    this.btnDelete.Enabled = false;
                    this.btnNew.Enabled = true ;
                    this.btnCancel.Enabled = false;
                    this.btnTallyCalculate.Enabled = false;
                    this.FuntoolStripMenuItem.Enabled = false ;
                    this.btnCopyTo.Enabled = false;
                    break;
                case FormStatus.Query:
                    BaseFunctions.ControlEnabled(this.toolStrip, false);
                    this.btnUpdate.Enabled = false;
                    this.btnDelete.Enabled = false;
                    this.btnNew.Enabled  = true  ;
                    this.btnCancel.Enabled = false;
                    this.btnTallyCalculate.Enabled = false;
                    this.FuntoolStripMenuItem.Enabled = false;
                    this.btnCopyTo.Enabled = false;
                    break;
                case FormStatus.Update:
                    BaseFunctions.ControlEnabled(this.toolStrip, false);
                    this.btnUpdate.Enabled = true;
                    this.btnDelete.Enabled = true;
                    this.btnNew.Enabled = false ;
                    this.btnCancel.Enabled = true;
                    this.btnAddLine.Enabled = true;
                    this.btnTallyCalculate.Enabled = true;
                    this.FuntoolStripMenuItem.Enabled = true;
                    this.btnCopyTo.Enabled = true;
                    this.btnCopyBOMToLabour.Enabled = true;
                    break;
                case FormStatus.Loading:
                    break;

            }

            //this.btnToExcel.Visible = (this.formStatus == FormStatus.Delete || this.formStatus == FormStatus.Query) && SysVar.AbleToExcel;
            this.btnToExcel.Visible = SysVar.AbleToExcel;
            //this.btnToExcel.Enabled = this.formStatus == FormStatus.Delete || this.formStatus == FormStatus.Query;
            this.btnToExcel.Enabled = true ;
            btnApprovalHistory.Enabled = true;
            this.btnTallyCalculate.Enabled = CvtFunc.ToBoolean( DataFunctions.GetFieldValue ( mdbcon ,"muser","AbleToChangeBOMFormula","username='"+ SysVar.UserName +"'"));

            newToolStripMenuItem.Enabled = btnNew.Enabled;
            cancelToolStripMenuItem.Enabled = btnCancel.Enabled;
            deleteToolStripMenuItem.Enabled = btnDelete.Enabled;
            saveToolStripMenuItem.Enabled = btnUpdate.Enabled;

            this.btnTop.Enabled = true;
            this.btnBottom.Enabled = true;
            this.btnPrev.Enabled = true;
            this.btnNext.Enabled = true;
            this.btnHelp.Enabled = true;
            this.btnExit.Enabled = true;


            this.btnTop.Visible = false;
            this.btnBottom.Visible = false;
            this.btnPrev.Visible = false;
            this.btnNext.Visible = false;
        }
        public override void SetOtherStatus()
        {
            mblnSettingStatus = true;

            switch (this.formStatus)
            {
                case FormStatus.AddNew:
                    this.txtProductName.Focus();
                    break;
                case FormStatus.Delete:
                    this.btnNew.Enabled = false;
                    break;
                case FormStatus.Query:
                    break;
                case FormStatus.Update:
                    this.btnNew.Enabled = true;
                    SetApprovalControlEnable();
                    SetControlByApproLevel();
                    break;
                case FormStatus.Loading:
                    this.btnNew.Enabled = false;
                    break;
            }
            mblnSettingStatus = false;
        }

        private void ShowFormula(int intRow)
        {
            if (this.dgvBOM.Rows[intRow] == null) return;
            string strRecID = CvtFunc.ToString(this.dgvBOM.Rows[intRow].Cells[(int)DtlCol.RecID].Value);
            if (CvtFunc.ToDouble(strRecID) <= 0)
            {
                txtCalFormula.Text = "";
                return;
            }

            txtCalFormula.Text = DataFunctions.GetFieldValue(mdbcon, "rmWKProductFormula", "WKFormula", "BOMRecID='" + strRecID + "'");
        }


        public override void ShowBaseData()
        {
            base.ShowBaseData();
        }

        protected override void ShowOtherData()
        {
            base.ShowOtherData();
            if (this.formStatus != FormStatus.Delete)
            {
                long lngRecID = CvtFunc.ToLong(DataFunctions.GetFieldValue("rmProduct", "RecID", "ProductFItemID='" + txtProductFItemID.Text + "'"));
                frmParameter.FillContent(lngRecID.ToString());
                InitGridDtl();
                FillDtl(txtCategoryID.Text, txtSetID.Text,txtProductFItemID.Text,txtTechnicsName.Text  );
                ShowLabourCost();
                ShowSemiProduct();
            }
            FillHdrData(txtCategoryID.Text, txtSetID.Text, txtProductFItemID.Text, txtTechnicsName.Text);
            ShowWorkCost();
        }

        private void FillHdrData(string strCategoryID, string strSetID, string strProductFItemID, string strTechnicsName)
        {
            string strSQL = "select * from rmProductBOMHdr where CategoryID='{0}' and SetID='{1}' and ProductFItemID='{2}' and TechnicsName='{3}' ";
            strSQL = string.Format(strSQL, strCategoryID, strSetID, strProductFItemID, strTechnicsName);
            DBAccess dbcon = new DBAccess(false, false);
            DataRow drHdr = dbcon.GetDataFirstRow(strSQL);
            if (drHdr != null)
            {
                //TotalLabourCost,TotalWastageCost,TotalDetailCost,TotalCost
                txtTotalDetailCost.Text = BaseFunctions.FormatNumeric(drHdr["TotalDetailCost"], "Ns.2");
                txtTotalWastageCost.Text = BaseFunctions.FormatNumeric(drHdr["TotalWastageCost"], "Ns.2");
                txtTotalLabourCost.Text = BaseFunctions.FormatNumeric(drHdr["TotalLabourCost"], "Ns.2");
                txtTotalCost.Text = BaseFunctions.FormatNumeric(drHdr["TotalCost"], "Ns.2");
                txtTotalWorkCost.Text = BaseFunctions.FormatNumeric(drHdr["TotalWorkCost"], "Ns.2");
                txtStandardUnitCost.Text = BaseFunctions.FormatNumeric(drHdr["StandardUnitCost"], "Ns.2"); 
            }
        }

        public override void RefreshOverView()
        {
            base.RefreshOverView();
            if (this.RecID != -1)
                this.dgList.RecID = this.RecID;
        }

        private void FillLookUpInfo()
        {
            SetFieldLookUpInfo("CategoryName", "rmCategory", "CategoryName", "ubtCategoryName");
            SetFieldLookUpInfo("SetName", "rmSet", "SetName", "ubtSetName");
            
            SetFieldLookUpInfo("CategoryID", "rmCategory", "CategoryID", "ubtCategoryName");
            SetFieldLookUpInfo("SetID", "rmSet", "SetID", "ubtSetName");

            SetFieldLookUpInfo("ProductName", "rmProduct", "ProductName", "ubtProductName");
            SetFieldLookUpInfo("ProductID", "rmProduct", "ProductID", "ubtProductName");
            SetFieldLookUpInfo("ProductFItemID", "rmProduct", "ProductFItemID", "ubtProductName");
            SetFieldLookUpInfo("ProductType", "rmProduct", "ProductType", "ubtProductName");            
        }

        #endregion Form Functions***


        #region Grid
        private void InitGridDtl()
        {
            // RowSeqNo = 0,SeqNo,WKName,WKRemark,CategoryName,SetName
            // IsKeyWK,  ItemNo, ItemName, Price, PriceUnit,
            // Qty, WastageRate, RatedCost,LabourCost, TotalCost,         
            this.dgvBOM.Columns.Clear();
            this.dgvBOM.Rows.Clear();

            DataGridViewTextBoxColumn colRowSeqNo = new DataGridViewTextBoxColumn();
            colRowSeqNo.HeaderText = "序号";
            colRowSeqNo.Visible = true;
            colRowSeqNo.Name = "RowSeqNo";
            colRowSeqNo.Width = 50;
            colRowSeqNo.ReadOnly = true;
            colRowSeqNo.SortMode = DataGridViewColumnSortMode.NotSortable ;

            DataGridViewTextBoxColumn colSeqNo = new DataGridViewTextBoxColumn();
            colSeqNo.HeaderText = "序号";
            colSeqNo.Visible = false;
            colSeqNo.Name = "SeqNo";
            colSeqNo.Width = 50;
            colSeqNo.ReadOnly = false;
            colSeqNo.SortMode = DataGridViewColumnSortMode.NotSortable;

            DataGridViewTextBoxColumn colProductFItemID = new DataGridViewTextBoxColumn();
            colProductFItemID.HeaderText = "成品编码";
            colProductFItemID.Visible = false;
            colProductFItemID.Name = "ProductFItemID";
            colProductFItemID.Width = 50;
            colProductFItemID.ReadOnly = false;
            colProductFItemID.SortMode = DataGridViewColumnSortMode.NotSortable;

            TextLookUpColumn colProductName = new TextLookUpColumn();
            colProductName.HeaderText = "产品名称";
            colProductName.Width = 150;
            colProductName.Name = "ProductName";
            colProductName.ReadOnly = false;
            colProductName.Visible = false;
            colProductName.SortMode = DataGridViewColumnSortMode.NotSortable;

            TextLookUpColumn colTechnicsName = new TextLookUpColumn();
            colTechnicsName.HeaderText = "工艺名称";
            colTechnicsName.Width = 150;
            colTechnicsName.Name = "TechnicsName";
            colTechnicsName.ReadOnly = false;
            colTechnicsName.Visible = false;
            colTechnicsName.SortMode = DataGridViewColumnSortMode.NotSortable;

            DataGridViewListColumn colWKID = new DataGridViewListColumn();
            colWKID.HeaderText = "工序编号";
            colWKID.Width = 0;
            colWKID.Name = "WKID";
            colWKID.ReadOnly = true;
            colWKID.Visible = false;

            TextLookUpColumn colWKName = new TextLookUpColumn();
            colWKName.HeaderText = "工序名称";
            colWKName.Width = 150;
            colWKName.Name = "WKName";
            colWKName.ReadOnly = false;
            colWKName.SortMode = DataGridViewColumnSortMode.NotSortable;

            DataGridViewListColumn colWKRemark = new DataGridViewListColumn();
            colWKRemark.HeaderText = "工序描述";
            colWKRemark.Width = 0;
            colWKRemark.Name = "WKRemark";
            colWKRemark.ReadOnly = true;
            colWKRemark.SortMode = DataGridViewColumnSortMode.NotSortable;

            DataGridViewListColumn colCategoryID = new DataGridViewListColumn();
            colCategoryID.HeaderText = "类别编码";
            colCategoryID.Width = 80;
            colCategoryID.Name = "CategoryID";
            colCategoryID.ReadOnly = false;
            colCategoryID.Visible = false;
            colCategoryID.SortMode = DataGridViewColumnSortMode.NotSortable;

            DataGridViewListColumn colCategoryName = new DataGridViewListColumn();
            colCategoryName.HeaderText = "类别名称";
            colCategoryName.Width = 80;
            colCategoryName.Name = "CategoryName";
            colCategoryName.ReadOnly = false;
            colCategoryName.Visible = false;
            colCategoryName.SortMode = DataGridViewColumnSortMode.NotSortable;

            DataGridViewListColumn colSetID = new DataGridViewListColumn();
            colSetID.HeaderText = "系列编码";
            colSetID.Width = 80;
            colSetID.Name = "SetID";
            colSetID.ReadOnly = false;
            colSetID.Visible = false;
            colSetID.SortMode = DataGridViewColumnSortMode.NotSortable;

            DataGridViewListColumn colSetName = new DataGridViewListColumn();
            colSetName.HeaderText = "系列名称";
            colSetName.Width = 80;
            colSetName.Name = "SetName";
            colSetName.ReadOnly = false;
            colSetName.Visible = false;
            colSetName.SortMode = DataGridViewColumnSortMode.NotSortable;

            DataGridViewCheckBoxColumn colKeyWK = new DataGridViewCheckBoxColumn();
            colKeyWK.HeaderText = "关键工序";
            colKeyWK.Width = 70;
            colKeyWK.Name = "isKeyWK";
            colKeyWK.ReadOnly = true;
            colKeyWK.Visible = false;
            colKeyWK.Resizable = DataGridViewTriState.False;
            colKeyWK.SortMode = DataGridViewColumnSortMode.NotSortable;

            DataGridViewCheckBoxColumn colInputWK = new DataGridViewCheckBoxColumn();
            colInputWK.HeaderText = "投料工序";
            colInputWK.Width = 70;
            colInputWK.Name = "isInputWK";
            colInputWK.ReadOnly = true;
            colInputWK.Visible = false;
            colInputWK.Resizable = DataGridViewTriState.False;
            colInputWK.SortMode = DataGridViewColumnSortMode.NotSortable;

            //ItemNo, ItemName, Price, PriceUnit,Qty, WastageRate,
            DataGridViewTextBoxColumn colFItemID = new DataGridViewTextBoxColumn();
            colFItemID.HeaderText = "物料内码";
            colFItemID.Visible = false ;
            colFItemID.Width = 120;
            colFItemID.Name = "FItemID";
            colFItemID.SortMode = DataGridViewColumnSortMode.NotSortable;

            TextLookUpColumn colItemNo = new TextLookUpColumn();
            colItemNo.HeaderText = "材料代码";
            colItemNo.Width = 100;
            colItemNo.Name = "ItemNo";
            colItemNo.ReadOnly = false;
            colItemNo.SortMode = DataGridViewColumnSortMode.NotSortable;

            DataGridViewTextBoxColumn colItemName = new DataGridViewTextBoxColumn();
            colItemName.HeaderText = "材料名称";
            colItemName.Visible = true;
            colItemName.Width = 120;
            colItemName.Name = "ItemName";
            colItemName.SortMode = DataGridViewColumnSortMode.NotSortable;

            TextLookUpColumn colSupNo = new TextLookUpColumn();
            colSupNo.HeaderText = "供应商代码";
            colSupNo.Width = 100;
            colSupNo.Name = "SupNo";
            colSupNo.ReadOnly = false;
            colSupNo.Visible = false;
            colSupNo.SortMode = DataGridViewColumnSortMode.NotSortable;

            DataGridViewTextBoxColumn colSupName = new DataGridViewTextBoxColumn();
            colSupName.HeaderText = "供应商名称";
            colSupName.Visible = true;
            colSupName.Width = 120;
            colSupName.Visible = false;
            colSupName.Name = "SupName";
            colSupName.SortMode = DataGridViewColumnSortMode.NotSortable;

            DataGridViewTextBoxColumn colPrice = new DataGridViewTextBoxColumn();
            colPrice.HeaderText = "单价";
            colPrice.Visible = true;
            colPrice.Width = 80;
            colPrice.Name = "Price";
            colPrice.SortMode = DataGridViewColumnSortMode.NotSortable;
            colPrice.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;
            colPrice.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;

            DataGridViewTextBoxColumn colPriceUnit = new DataGridViewTextBoxColumn();
            colPriceUnit.HeaderText = "单位";
            colPriceUnit.Visible = true;
            colPriceUnit.Width = 60;
            colPriceUnit.Name = "PriceUnit";
            colPriceUnit.SortMode = DataGridViewColumnSortMode.NotSortable;

            DataGridViewTextBoxColumn colPlanTreatCost = new DataGridViewTextBoxColumn();
            colPlanTreatCost.HeaderText = "计划基本单价";
            colPlanTreatCost.Visible = false;
            colPlanTreatCost.Width = 60;
            colPlanTreatCost.Name = "PlanTreatCost";
            colPlanTreatCost.SortMode = DataGridViewColumnSortMode.NotSortable;

            DataGridViewTextBoxColumn colQty = new DataGridViewTextBoxColumn();
            colQty.HeaderText = "定额数量";
            colQty.Width = 70;
            colQty.Visible = true;
            colQty.Name = "Qty";
            colQty.SortMode = DataGridViewColumnSortMode.NotSortable;
            colQty.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            colQty.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;

            DataGridViewTextBoxColumn colWastageRate = new DataGridViewTextBoxColumn();
            colWastageRate.HeaderText = "损耗率%";
            colWastageRate.Visible = true;
            colWastageRate.Width = 50;
            colWastageRate.Name = "WastageRate";
            colWastageRate.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;
            colWastageRate.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;

            // QtyWastage,DetailCost,LabourCost, TotalCost,
            DataGridViewTextBoxColumn colQtyWastage = new DataGridViewTextBoxColumn();
            colQtyWastage.HeaderText = "损耗数量";
            colQtyWastage.Visible = false;
            colQtyWastage.Width = 70;
            colQtyWastage.Name = "QtyWastage";
            colQtyWastage.SortMode = DataGridViewColumnSortMode.NotSortable;
            colQtyWastage.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            colQtyWastage.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;

            DataGridViewTextBoxColumn colDetailCost = new DataGridViewTextBoxColumn();
            colDetailCost.HeaderText = "定额成本";
            colDetailCost.Visible = true;
            colDetailCost.Width = 70;
            colDetailCost.Name = "DetailCost";
            colDetailCost.SortMode = DataGridViewColumnSortMode.NotSortable;
            colDetailCost.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            colDetailCost.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;

            DataGridViewTextBoxColumn colLabourCost = new DataGridViewTextBoxColumn();
            colLabourCost.HeaderText = "人工成本";
            colLabourCost.Visible = false ;
            colLabourCost.Width = 70;
            colLabourCost.Name = "LabourCost";
            colLabourCost.SortMode = DataGridViewColumnSortMode.NotSortable;
            colLabourCost.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;
            colLabourCost.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;

            DataGridViewTextBoxColumn colTotalCost = new DataGridViewTextBoxColumn();
            colTotalCost.HeaderText = "总单价";
            colTotalCost.Visible = true;
            colTotalCost.Width = 80;
            colTotalCost.Name = "TotalCost";

            colTotalCost.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            colTotalCost.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;
            colTotalCost.SortMode = DataGridViewColumnSortMode.NotSortable;

            DataGridViewTextBoxColumn colRecID = new DataGridViewTextBoxColumn();
            colRecID.HeaderText = "RecID";
            colRecID.Visible = false;
            colRecID.Name = "RecID";

            DataGridViewTextBoxColumn colValueChanged = new DataGridViewTextBoxColumn();
            colValueChanged.HeaderText = "ValueChanged";
            colValueChanged.Visible = false;
            colValueChanged.Name = "ValueChanged";

            DataGridViewImageColumn colDel = new DataGridViewImageColumn();
            Bitmap delbitmap = new Bitmap(this.iglSource.Images["del.ico"]);
            colDel.Width = 20;
            colDel.Name = "DelLine";
            colDel.HeaderText = "";
            colDel.Resizable = DataGridViewTriState.False;

            colItemName.ReadOnly = true;
            colSupNo.ReadOnly = true;
            colSupName.ReadOnly = true;

            this.dgvBOM.Columns.AddRange(new DataGridViewColumn[] { colRowSeqNo, colSeqNo, colProductFItemID , colProductName,colTechnicsName,colWKID  ,colWKName,
                                                                    colWKRemark, colKeyWK, colInputWK, colCategoryID   ,colCategoryName, colSetID ,colSetName ,
                                                                    colFItemID, colItemNo, colItemName,colSupNo,colSupName , colPrice, colPriceUnit,colPlanTreatCost,colQty, colWastageRate,
                                                                    colQtyWastage,colDetailCost,colLabourCost, colTotalCost,
                                                                    colRecID, colValueChanged, colDel });

            mDtlColumnReadOnlyArray = new bool[dgvBOM.Columns.Count];
            string[] ColumnWidthArray = DataFunctions.GetGridColumnWidthString(this.Name, this.CurrentMenuInfo.iParameter, SysVar.UserName, this.Name + "." + this.dgvBOM.Name).Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            for (int i = 0; i < dgvBOM.Columns.Count; i++)
            {
                mDtlColumnReadOnlyArray[i] = dgvBOM.Columns[i].ReadOnly;
                if (ColumnWidthArray.Length == dgvBOM.Columns.Count) dgvBOM.Columns[i].Width = CvtFunc.ToInt(ColumnWidthArray[i]);
            }
            
            this.dgvBOM.EditMode = DataGridViewEditMode.EditOnEnter;
            this.dgvBOM.RowTemplate.Height = 20;
            this.dgvBOM.RowHeadersWidth = 23;
            this.dgvBOM.RowHeadersBorderStyle = DataGridViewHeaderBorderStyle.None;
            this.dgvBOM.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.DisableResizing;
            this.dgvBOM.ColumnHeadersHeight = 30;
            this.dgvBOM.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
            this.dgvBOM.SelectionMode = DataGridViewSelectionMode.CellSelect;
            this.dgvBOM.AllowUserToResizeRows = false;

        }
        private void InitGridDtlLabourCost()
        {
           
            //RowSeqNo =0,
            //SeqNo,WKName,WKRemark,CategoryName , SetName  ,ProductName     ,ItemNo                  
            this.dgvLabourCost.Columns.Clear();
            this.dgvLabourCost.Rows.Clear();

            DataGridViewTextBoxColumn colRowSeqNo = new DataGridViewTextBoxColumn();
            colRowSeqNo.HeaderText = "序号";
            colRowSeqNo.Visible = true;
            colRowSeqNo.Name = "RowSeqNo";
            colRowSeqNo.Width = 50;
            colRowSeqNo.ReadOnly = true;

            DataGridViewTextBoxColumn colHdrSeqNo = new DataGridViewTextBoxColumn();
            colHdrSeqNo.HeaderText = "BOM序号";
            colHdrSeqNo.Visible = false;
            colHdrSeqNo.Name = "BOMSeqNo";
            colHdrSeqNo.Width = 50;
            colHdrSeqNo.ReadOnly = true;

            DataGridViewTextBoxColumn colSeqNo = new DataGridViewTextBoxColumn();
            colSeqNo.HeaderText = "序号";
            colSeqNo.Visible = false;
            colSeqNo.Name = "SeqNo";
            colSeqNo.Width = 50;
            colSeqNo.ReadOnly = false;

            DataGridViewListColumn colWKID = new DataGridViewListColumn();
            colWKID.HeaderText = "工序编号";
            colWKID.Width = 0;
            colWKID.Name = "WKID";
            colWKID.ReadOnly = true;
            colWKID.Visible = false;

            TextLookUpColumn colWKName = new TextLookUpColumn();
            colWKName.HeaderText = "工序名称";
            colWKName.Width = 150;
            colWKName.Name = "WKName";
            colWKName.ReadOnly = false;

            DataGridViewListColumn colWKPriceType = new DataGridViewListColumn();
            colWKPriceType.HeaderText = "工价类别";
            colWKPriceType.Width = 100;
            colWKPriceType.Name = "WKPriceType";
            colWKPriceType.ReadOnly = true;

            DataGridViewListColumn colWKRemark = new DataGridViewListColumn();
            colWKRemark.HeaderText = "工序描述";
            colWKRemark.Width = 0;
            colWKRemark.Name = "WKRemark";
            colWKRemark.ReadOnly = true;

            DataGridViewCheckBoxColumn colKeyWK = new DataGridViewCheckBoxColumn();
            colKeyWK.HeaderText = "关键工序";
            colKeyWK.Width = 70;
            colKeyWK.Name = "isKeyWK";
            colKeyWK.ReadOnly = false ;
            colKeyWK.Resizable = DataGridViewTriState.False;
            colKeyWK.SortMode = DataGridViewColumnSortMode.NotSortable;

            DataGridViewTextBoxColumn colWKOutName = new DataGridViewTextBoxColumn();
            colWKOutName.HeaderText = "工序产出";
            colWKOutName.Width = 70;
            colWKOutName.Name = "WKOutName";
            colWKOutName.ReadOnly = false;
            colWKOutName.Resizable = DataGridViewTriState.False;
            colWKOutName.SortMode = DataGridViewColumnSortMode.NotSortable;


            DataGridViewListColumn colCategoryID = new DataGridViewListColumn();
            colCategoryID.HeaderText = "类别编码";
            colCategoryID.Width = 80;
            colCategoryID.Name = "CategoryID";
            colCategoryID.ReadOnly = false;
            colCategoryID.Visible = false;

            DataGridViewListColumn colCategoryName = new DataGridViewListColumn();
            colCategoryName.HeaderText = "类别名称";
            colCategoryName.Width = 80;
            colCategoryName.Name = "CategoryName";
            colCategoryName.ReadOnly = false;
            colCategoryName.Visible = false;

            DataGridViewListColumn colSetID = new DataGridViewListColumn();
            colSetID.HeaderText = "系列编码";
            colSetID.Width = 80;
            colSetID.Name = "SetID";
            colSetID.ReadOnly = false;
            colSetID.Visible = false;

            DataGridViewListColumn colSetName = new DataGridViewListColumn();
            colSetName.HeaderText = "系列名称";
            colSetName.Width = 80;
            colSetName.Name = "SetName";
            colSetName.ReadOnly = false;
            colSetName.Visible = false;

            DataGridViewListColumn colProductFItemID = new DataGridViewListColumn();
            colProductFItemID.HeaderText = "产成品编码";
            colProductFItemID.Width = 80;
            colProductFItemID.Name = "ProductFItemID";
            colProductFItemID.ReadOnly = false;
            colProductFItemID.Visible = false;

            DataGridViewListColumn colProductName = new DataGridViewListColumn();
            colProductName.HeaderText = "产成品名称";
            colProductName.Width = 80;
            colProductName.Name = "ProductName";
            colProductName.ReadOnly = false;
            colProductName.Visible = false;

            DataGridViewListColumn colTechnicsName = new DataGridViewListColumn();
            colTechnicsName.HeaderText = "工艺名称";
            colTechnicsName.Width = 150;
            colTechnicsName.Name = "TechnicsName";
            colTechnicsName.ReadOnly = false;
            colTechnicsName.Visible = false;
            colTechnicsName.SortMode = DataGridViewColumnSortMode.NotSortable;

            DataGridViewTextBoxColumn colFItemID = new DataGridViewTextBoxColumn();
            colFItemID.HeaderText = "物料内码";
            colFItemID.Visible = false ;
            colFItemID.Width = 120;
            colFItemID.Name = "FItemID";
            colFItemID.SortMode = DataGridViewColumnSortMode.NotSortable;

            TextLookUpColumn colItemNo = new TextLookUpColumn();
            colItemNo.HeaderText = "物料代码";
            colItemNo.Width = 80;
            colItemNo.Name = "ItemNo";
            colItemNo.ReadOnly = false;
            colItemNo.Visible = false;

            DataGridViewTextBoxColumn colItemName = new DataGridViewTextBoxColumn();
            colItemName.HeaderText = "物料名称";
            colItemName.Visible = false;
            colItemName.Name = "ItemName";
            colItemName.Width = 50;
            colItemName.ReadOnly = false;

            //CalUnit,CutType,WorkQty, TotalQty,    //总数量            
            TextLookUpColumn colCalUnit = new TextLookUpColumn();
            colCalUnit.HeaderText = "计件单位";
            colCalUnit.Width = 100;
            colCalUnit.Name = "CalUnit";
            colCalUnit.ReadOnly = false;

            TextLookUpColumn colCutType = new TextLookUpColumn();
            colCutType.HeaderText = "分切系数";
            colCutType.Visible = true;
            colCutType.Width = 70;
            colCutType.Name = "CutType";

            DataGridViewTextBoxColumn colWorkQty = new DataGridViewTextBoxColumn();
            colWorkQty.HeaderText = "总数量";
            colWorkQty.Width = 70;
            colWorkQty.Visible = true;
            colWorkQty.Name = "WorkQty";
            colWorkQty.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            colWorkQty.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;

            DataGridViewTextBoxColumn colTotalQty = new DataGridViewTextBoxColumn();
            colTotalQty.HeaderText = "计量数量";
            colTotalQty.Width = 60;
            colTotalQty.Visible = true ;
            colTotalQty.Name = "TotalQty";
            colTotalQty.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            colTotalQty.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;

            //StandardQty, //10小时额定产量
            //spendHours,   //预计用工时间
            //StandardWage,  // 固定工资          
            DataGridViewTextBoxColumn colStandardQty = new DataGridViewTextBoxColumn();
            colStandardQty.HeaderText = "额定产量(10小时)";
            colStandardQty.Visible = true;
            colStandardQty.Width = 50;
            colStandardQty.Name = "StandardQty";

            DataGridViewTextBoxColumn colSpendHours = new DataGridViewTextBoxColumn();
            colSpendHours.HeaderText = "耗用工时";
            colSpendHours.Visible = true ;
            colSpendHours.Width = 45;
            colSpendHours.Name = "SpendHours";
            colSpendHours.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;
            colSpendHours.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;

            DataGridViewTextBoxColumn colStandardWage = new DataGridViewTextBoxColumn();
            colStandardWage.HeaderText = "固定工资";
            colStandardWage.Visible = true;
            colStandardWage.Width = 70;
            colStandardWage.Name = "StandardWage";
            colStandardWage.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;
            colStandardWage.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;

            //StandardWage26, //26天标准工资
            //UnitCost,        //记件工价
            //Remark,         //备注 
            DataGridViewTextBoxColumn colStandardWage26 = new DataGridViewTextBoxColumn();
            colStandardWage26.HeaderText = "标准工资(26天)";
            colStandardWage26.Visible = true;
            colStandardWage26.Width = 60;
            colStandardWage26.Name = "StandardWage26";
            colStandardWage26.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            colStandardWage26.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;

            DataGridViewTextBoxColumn colUnitCost = new DataGridViewTextBoxColumn();
            colUnitCost.HeaderText = "计件工价";
            colUnitCost.Visible = true ;
            colUnitCost.Width = 65;
            colUnitCost.Name = "UnitCost";
            colUnitCost.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            colUnitCost.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;

            DataGridViewTextBoxColumn colTotUnitCost = new DataGridViewTextBoxColumn();
            colTotUnitCost.HeaderText = "计件工资";
            colTotUnitCost.Visible = true ;
            colTotUnitCost.Width = 70;
            colTotUnitCost.Name = "TotUnitCost";
            colTotUnitCost.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            colTotUnitCost.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;
            
            DataGridViewTextBoxColumn colDtlLaborTotCost = new DataGridViewTextBoxColumn();
            colDtlLaborTotCost.HeaderText = "人工成本";
            colDtlLaborTotCost.Visible = true;
            colDtlLaborTotCost.Width = 70;
            colDtlLaborTotCost.Name = "";
            colDtlLaborTotCost.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            colDtlLaborTotCost.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;
            
            DataGridViewTextBoxColumn colWorkCost = new DataGridViewTextBoxColumn();
            colWorkCost.HeaderText = "工时费用标准";
            colWorkCost.Visible = true ;
            colWorkCost.Width = 60;
            colWorkCost.Name = "WorkCost";
            colWorkCost.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            colWorkCost.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;

            DataGridViewTextBoxColumn colDetailTotWorkCost = new DataGridViewTextBoxColumn();
            colDetailTotWorkCost.HeaderText = "工时费用";
            colDetailTotWorkCost.Visible = true ;
            colDetailTotWorkCost.Width = 60;
            colDetailTotWorkCost.Name = "DetailTotWorkCost";
            colDetailTotWorkCost.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            colDetailTotWorkCost.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;


            DataGridViewTextBoxColumn colRemark = new DataGridViewTextBoxColumn();
            colRemark.HeaderText = "备注";
            colRemark.Visible = true;
            colRemark.Width = 80;
            colRemark.Name = "Remark";
            colRemark.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            colRemark.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;

            DataGridViewTextBoxColumn colRecID = new DataGridViewTextBoxColumn();
            colRecID.HeaderText = "RecID";
            colRecID.Visible = false;
            colRecID.Name = "RecID";

            DataGridViewTextBoxColumn colValueChanged = new DataGridViewTextBoxColumn();
            colValueChanged.HeaderText = "ValueChanged";
            colValueChanged.Visible = false;
            colValueChanged.Name = "ValueChanged";

            DataGridViewImageColumn colDel = new DataGridViewImageColumn();
            Bitmap delbitmap = new Bitmap(this.iglSource.Images["del.ico"]);
            colDel.Width = 20;
            colDel.Name = "DelLine";
            colDel.HeaderText = "";
            colDel.Resizable = DataGridViewTriState.False;

            //RowSeqNo =0,
            //SeqNo,WKName,WKRemark,CategoryName , SetName   
            //CalUnit,CutType, TotalQty,    //总数量 
            //StandardQty, //10小时额定产量
            //spendHours,   //预计用工时间
            //StandardWage,  // 固定工资   
            //StandardWage26, //26天标准工资
            //UnitCost,        //记件工价
            //Remark,         //备注 
            this.dgvLabourCost.Columns.AddRange(new DataGridViewColumn[] { colRowSeqNo,colHdrSeqNo, colSeqNo, colWKID  ,colWKName, colWKPriceType ,colWKRemark,colKeyWK , colWKOutName , colCategoryID ,colCategoryName, colSetID ,colSetName , 
                                                                    colProductFItemID,  colProductName,colTechnicsName,colFItemID,colItemNo , colItemName ,
                                                                    colCalUnit , colCutType  , colWorkQty  ,colTotalQty , colStandardQty  ,colSpendHours, colStandardWage  ,
                                                                    colStandardWage26, colUnitCost,colTotUnitCost,colDtlLaborTotCost,colWorkCost,colDetailTotWorkCost , colRemark ,
                                                                    colRecID, colValueChanged, colDel  });

            mDtlColumnReadOnlyArray_LabourCost = new bool[dgvLabourCost.Columns.Count];
            string[] ColumnWidthArray = DataFunctions.GetGridColumnWidthString(this.Name, this.CurrentMenuInfo.iParameter, SysVar.UserName, this.Name + "." + this.dgvLabourCost.Name).Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            for (int i = 0; i < dgvLabourCost.Columns.Count; i++)
            {
                mDtlColumnReadOnlyArray_LabourCost[i] = dgvLabourCost.Columns[i].ReadOnly;
                if (ColumnWidthArray.Length == dgvLabourCost.Columns.Count) dgvLabourCost.Columns[i].Width = CvtFunc.ToInt(ColumnWidthArray[i]);
            }

            this.dgvLabourCost.EditMode = DataGridViewEditMode.EditOnEnter;
            this.dgvLabourCost.RowTemplate.Height = 20;
            this.dgvLabourCost.RowHeadersWidth = 23;
            this.dgvLabourCost.RowHeadersBorderStyle = DataGridViewHeaderBorderStyle.None;
            this.dgvLabourCost.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.DisableResizing;
            this.dgvLabourCost.ColumnHeadersHeight = 40;
            this.dgvLabourCost.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
            this.dgvLabourCost.SelectionMode = DataGridViewSelectionMode.CellSelect;
            this.dgvLabourCost.AllowUserToResizeRows = false;

        }

        private void AddDtlRow(string strGridName)
        {
            AddDtlRow(strGridName, -1);
        }

        private void RefershRowSeqNo( string strGridName)
        {
            DBAccess dbCon = new DBAccess(false, false);
            if (this.tbcMain.SelectedTab == tbpBOM)
            {
                foreach (DataGridViewRow dgvRow in this.dgvBOM.Rows)
                {
                    string strErrMsg = "";
                    dgvRow.Cells[(int)DtlCol.RowSeqNo].Value = dgvRow.Index + 1;
                    if (this.dgvBOM.CurrentRow.Index < dgvRow.Index)
                    {
                        if (CvtFunc.ToDouble(dgvRow.Cells[(int)DtlCol.RecID].Value) > 0)
                        {
                            string strSQL = "update rmProductBOMDetail set RowSeqNo='" + (dgvRow.Index + 1) + "' where RecID='" + dgvRow.Cells[(int)DtlCol.RecID].Value + "'";
                            dbCon.ExecuteSql(strSQL);
                        }
                    }
                }
            }
            else if (this.tbcMain.SelectedTab == tbpOtherCost)
            {
                foreach (DataGridViewRow dgvRow in this.dgvLabourCost.Rows)
                {
                    string strErrMsg = "";
                    dgvRow.Cells[(int)DtlCol.RowSeqNo].Value = dgvRow.Index + 1;
                    if (this.dgvLabourCost.CurrentRow.Index < dgvRow.Index)
                    {
                        if (CvtFunc.ToDouble(dgvRow.Cells[(int)LabourCostCol.RecID].Value) > 0)
                        {
                            string strSQL = "update rmProductBOMLabourCost set RowSeqNo='" + (dgvRow.Index + 1) + "' where RecID='" + dgvRow.Cells[(int)LabourCostCol.RecID].Value + "'";
                            dbCon.ExecuteSql(strSQL);
                        }
                    }
                }
            }
            dbCon.CloseCon(); 
        }

        private void AddDtlRow(string strGridName, double iRow)
        {
            if (strGridName == dgvBOM.Name)
            {
                if (this.dgvBOM.ReadOnly) return;
                int intRow = CvtFunc.ToInt(iRow);
                m_bCanTrigerCellValueChangedEven = false;
                if (iRow >= 0)
                {
                    intRow++;
                    this.dgvBOM.Rows.Insert(intRow, 1);
                }
                else
                {
                    this.dgvBOM.Rows.Add();
                    intRow = this.dgvBOM.Rows.Count - 1;
                }
                dgvBOM.Rows[intRow].Cells[(int)DtlCol.RowSeqNo].Value = dgvBOM.Rows.Count.ToString();
                dgvBOM.Rows[intRow].Cells[(int)DtlCol.SeqNo].Value = CvtFunc.ToString(CvtFunc.ToDouble(DataFunctions.GetFieldValue("rmProductBOMDetail", "max(SeqNo)", "CategoryID='" + txtCategoryID.Text + "' and SetID='" + txtSetID.Name + "' and TechnicsName='"+ txtTechnicsName.Text +"'")) + 1);
                dgvBOM.Rows[intRow].Cells[(int)DtlCol.ProductFItemID].Value = txtProductFItemID.Text;
                dgvBOM.Rows[intRow].Cells[(int)DtlCol.ProductName].Value = txtProductName.Text;
                dgvBOM.Rows[intRow].Cells[(int)DtlCol.TechnicsName].Value = txtTechnicsName.Text;
                dgvBOM.Rows[intRow].Cells[(int)DtlCol.CategoryID].Value = txtCategoryID.Text;
                dgvBOM.Rows[intRow].Cells[(int)DtlCol.CategoryName].Value = txtCategoryName.Text;
                dgvBOM.Rows[intRow].Cells[(int)DtlCol.SetID].Value = txtSetID.Text;
                dgvBOM.Rows[intRow].Cells[(int)DtlCol.SetName].Value = txtSetName.Text;
                dgvBOM.Rows[intRow].Cells[(int)DtlCol.IsKeyWK].Value = "false";
                if (dgvBOM.Rows.Count > 0 && intRow >= 1)
                {
                    dgvBOM.Rows[intRow].Cells[(int)DtlCol.WKID].Value = dgvBOM.Rows[intRow - 1].Cells[(int)DtlCol.WKID].Value;
                    dgvBOM.Rows[intRow].Cells[(int)DtlCol.WKRemark].Value = dgvBOM.Rows[intRow - 1].Cells[(int)DtlCol.WKRemark].Value;
                    dgvBOM.Rows[intRow].Cells[(int)DtlCol.WKName].Value = dgvBOM.Rows[intRow - 1].Cells[(int)DtlCol.WKName].Value;
                }
                else
                {
                    dgvBOM.Rows[intRow].Cells[(int)DtlCol.WKID].Value = "";
                    dgvBOM.Rows[intRow].Cells[(int)DtlCol.WKRemark].Value = "";
                    dgvBOM.Rows[intRow].Cells[(int)DtlCol.WKName].Value = "";
                }
                dgvBOM.Rows[intRow].Cells[(int)DtlCol.FItemID].Value = "0";
                dgvBOM.Rows[intRow].Cells[(int)DtlCol.ItemNo].Value = "";
                dgvBOM.Rows[intRow].Cells[(int)DtlCol.ItemName].Value = "";
                dgvBOM.Rows[intRow].Cells[(int)DtlCol.LabourCost].Value = "0.00";
                dgvBOM.Rows[intRow].Cells[(int)DtlCol.Price].Value = "0.00";
                dgvBOM.Rows[intRow].Cells[(int)DtlCol.PriceUnit].Value = "";
                dgvBOM.Rows[intRow].Cells[(int)DtlCol.Qty].Value = "0.00";
                dgvBOM.Rows[intRow].Cells[(int)DtlCol.QtyWastage].Value = "0.00";
                dgvBOM.Rows[intRow].Cells[(int)DtlCol.DetailCost].Value = "0.00";
                dgvBOM.Rows[intRow].Cells[(int)DtlCol.TotalCost].Value = "0.00";
                dgvBOM.Rows[intRow].Cells[(int)DtlCol.WastageRate].Value = "0.00";
                dgvBOM.Rows[intRow].Cells[(int)DtlCol.RecID].Value = -1;
                dgvBOM.Rows[intRow].Cells[(int)DtlCol.ValueChanged].Value = "0";
                dgvBOM.CurrentCell = dgvBOM.Rows[intRow].Cells[(int)DtlCol.WKName];
                m_bCanTrigerCellValueChangedEven = true;               
            }
            else if (strGridName == this.dgvLabourCost.Name)
            {
                if (dgvBOM.Rows.Count == 0) return;
                if (this.dgvLabourCost.ReadOnly) return;
                int intRow = CvtFunc.ToInt(iRow);
                m_bCanTrigerCellValueChangedEven_LabourCost = false;
                if (iRow >= 0)
                {
                    intRow++;
                    this.dgvLabourCost.Rows.Insert(intRow, 1);
                }
                else
                {
                    this.dgvLabourCost.Rows.Add();
                    intRow = this.dgvLabourCost.Rows.Count - 1;
                }
                dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.RowSeqNo].Value = dgvLabourCost.Rows.Count.ToString();

                string strBOMSeqNo = "0";
                string strItemNo ="";
                if (  dgvBOM.CurrentRow !=null )
                {
                    strBOMSeqNo = CvtFunc.ToString(dgvBOM.CurrentRow.Cells[(int)DtlCol.SeqNo].Value);
                    strItemNo = CvtFunc.ToString(dgvBOM.CurrentRow.Cells[(int)DtlCol.ItemNo].Value);
                }
                dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.BOMSeqNo].Value = strBOMSeqNo ;
                dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.ItemNo].Value = "" ;
                dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.ItemName].Value ="";

                dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.SeqNo].Value = CvtFunc.ToString(CvtFunc.ToDouble(DataFunctions.GetFieldValue("rmProductBOMLabourCost", "max(SeqNo)", "CategoryID='" + txtCategoryID.Text + "' and SetID='" + txtSetID.Name + "' and ProductFItemID='"+ txtProductFItemID.Text + "' and TechnicsName='" + txtTechnicsName.Text + "'")) + 1);
                
                dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.CategoryID].Value = txtCategoryID.Text;
                dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.SetID].Value = txtSetID.Text;
                dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.ProductFItemID].Value = txtProductFItemID.Text;
                
                dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.CategoryName].Value = txtCategoryName.Text;
                dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.SetName].Value = txtSetName.Text;
                dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.ProductName].Value = txtProductName.Text;
                dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.TechnicsName].Value = txtTechnicsName.Text;
               
                //if (dgvLabourCost.Rows.Count > 0 && intRow >=1)
                //{

                //    dgvLabourCost.Rows[intRow].Cells[(int)DtlCol.WKRemark].Value = dgvLabourCost.Rows[intRow-1].Cells[(int)DtlCol.WKRemark].Value;
                //    dgvLabourCost.Rows[intRow].Cells[(int)DtlCol.WKName].Value = dgvLabourCost.Rows[intRow-1].Cells[(int)DtlCol.WKName].Value;
                //}
                //else
                {
                    dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.WKRemark].Value = "";
                    dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.WKName].Value = "";
                }
                dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.CalUnit].Value = "";
                dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.CutType].Value = "1";
                dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.StandardQty].Value = "0.00";
                dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.StandardWage].Value = "0.00";
                dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.StandardWage26].Value = "";
                dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.TotalQty].Value = "0.00";
                dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.UnitCost].Value = "0.00";
                
                dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.UsedHours].Value = "0.00";
                dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.TotalQty].Value = "0.00";
                dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.Remark].Value = "";
                dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.RecID].Value = -1;
                this.dgvLabourCost.Columns[(int)LabourCostCol.WKName].ReadOnly = false ;
                dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.ValueChanged].Value = "0";
                dgvLabourCost.CurrentCell = dgvLabourCost.Rows[intRow].Cells[(int)LabourCostCol.WKName];
                m_bCanTrigerCellValueChangedEven_LabourCost = true;
            }
            RefershRowSeqNo(strGridName );
        }

        private bool CheckDtlRow(ref string strErrMsg)
        {
            bool bCheckResult = true;
            for (int i = 0; i < dgvBOM.ColumnCount - 1; i++)
            {
                bCheckResult = CheckDtlCell(i, ref strErrMsg);
                if (!bCheckResult) break;
            }
            return bCheckResult;
        }
        private bool CheckDtlRow_LabourCost(ref string strErrMsg)
        {
            bool bCheckResult = true;
            for (int i = 0; i < dgvLabourCost.ColumnCount - 1; i++)
            {
                bCheckResult = CheckDtlCell_LabourCost(i, ref strErrMsg);
                if (!bCheckResult) break;
            }
            return bCheckResult;
        }
        private bool CheckDtlCell(int iColumn, ref string strErrMsg)
        {
            bool bReturnValue = true;
            strErrMsg = "";
            string strValue = "";
            if (this.dgvBOM.CurrentRow != null && this.dgvBOM.CurrentRow.Cells[iColumn].Value != null)
            {
                strValue = this.dgvBOM.CurrentRow.Cells[iColumn].Value.ToString().TrimEnd();
            }
            switch ((DtlCol)iColumn)
            {
                case DtlCol.WKID :
                    if (strValue.Trim() == "")
                    {
                        strErrMsg = "工序编码不能空.";
                        return false;
                    }
                    if (!DataFunctions.CheckRecordExist("rmWorkingProcedure", strValue, "WorkingProcedureID"))
                    {
                        strErrMsg = "不存在的工序编码";
                        return false;
                    }
                    return true;
                case DtlCol.WKName:
                    if (strValue.Trim() == "")
                    {
                        strErrMsg = "工序名称不能空.";
                        return false;
                    }
                    if (!DataFunctions.CheckRecordExist("rmWorkingProcedure", strValue, "WorkingProcedureName"))
                    {
                        strErrMsg = "不存在的工序名称";
                        return false;
                    }
                    return true;
                case DtlCol.ItemNo:
                    if (strValue.Trim() == "" && CvtFunc.ToBoolean(this.dgvBOM.CurrentRow.Cells[(int)DtlCol.IsInputWK].Value))
                    {
                        strErrMsg = "投料工序的物料名称不能为空";
                        return false;
                    }
                    else if (!DataFunctions.CheckRecordExist("iminvmaster", strValue, "ItemNo") && strValue != "")
                    {
                        strErrMsg = "不存在的物料编码";
                        return false;
                    }
                    return true;
            }
            return bReturnValue;
        }
        private bool CheckDtlCell_LabourCost(int iColumn, ref string strErrMsg)
        {
            bool bReturnValue = true;
            strErrMsg = "";
            string strValue = "";
            if (this.dgvLabourCost.CurrentRow != null && this.dgvLabourCost.CurrentRow.Cells[iColumn].Value != null)
            {
                strValue = this.dgvLabourCost.CurrentRow.Cells[iColumn].Value.ToString().TrimEnd();
            }
            switch ((LabourCostCol)iColumn)
            {
                case LabourCostCol.WKID:
                    if (strValue.Trim() == "")
                    {
                        strErrMsg = "工序编码不能空.";
                        return false;
                    }
                    if (!DataFunctions.CheckRecordExist("rmWorkingProcedure", strValue, "WorkingProcedureID"))
                    {
                        strErrMsg = "不存在的工序编码";
                        return false;
                    }
                    return true;
                case LabourCostCol.WKName:
                    if (strValue.Trim() == "")
                    {
                        strErrMsg = "工序名称不能空.";
                        return false;
                    }
                    if (!DataFunctions.CheckRecordExist("rmWorkingProcedure", strValue, "WorkingProcedureName"))
                    {
                        strErrMsg = "不存在的工序名称";
                        return false;
                    }
                    return true;
                case LabourCostCol.ItemNo:
                    //if (strValue.Trim() == "" && CvtFunc.ToBoolean(this.dgvLabourCost.CurrentRow.Cells[(int)DtlCol.IsInputWK].Value))
                    //{
                    //    strErrMsg = "投料工序的物料名称不能为空";
                    //    return false;
                    //}
                    //else
                    if (!DataFunctions.CheckRecordExist("iminvmaster", strValue, "ItemNo") && strValue != "")
                    {
                        strErrMsg = "不存在的物料编码";
                        return false;
                    }
                    return true;
            }
            return bReturnValue;
        }

        private void btnAddLine_Click(object sender, EventArgs e)
        {
            string strErrMsg = string.Empty;
            if (this.tbcMain.SelectedTab == tbpBOM)
            {
                if (this.dgvBOM.Rows.Count == 0)
                {
                    AddDtlRow(this.dgvBOM.Name);
                }
                if (CheckDtlRow(ref strErrMsg))
                {
                    if (Update_Detail(this.dgvBOM.CurrentRow))
                    {
                        AddDtlRow(this.dgvBOM.Name, dgvBOM.CurrentCell.RowIndex);
                        RefershRowSeqNo( this.dgvBOM.Name );
                    }
                }
                else if (string.IsNullOrEmpty(strErrMsg))
                {
                    MessageBox.Show(strErrMsg, "", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
            else if (this.tbcMain.SelectedTab == tbpOtherCost)
            {                
                if (this.dgvLabourCost.Rows.Count == 0)
                {
                    AddDtlRow(this.dgvLabourCost.Name);
                }
                else if (CheckDtlRow_LabourCost(ref strErrMsg))
                {
                    if (Update_Detail_LabourCost(this.dgvLabourCost.CurrentRow))
                    {
                        AddDtlRow(this.dgvLabourCost.Name, dgvLabourCost.CurrentCell.RowIndex);
                    }
                }
                else if (!string.IsNullOrEmpty(strErrMsg))
                {
                    MessageBox.Show(strErrMsg, "", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
        }

        private bool Update_Detail(DataGridViewRow dgvRow)
        {
            if (this.formStatus == FormStatus.Query) return true ;
            if (dgvRow == null) return false;
            if (this.dgvBOM.ReadOnly) return true ;
            string strSQL = string.Empty;
            DBAccess dbcon = new DBAccess(false, false);
            try
            {
                dbcon.BeginTran();
                RMProductBOMHdrBRL rmBRL = new RMProductBOMHdrBRL();
                DataRow drBOM = dbcon.GetDataSet("select * from rmProductBOMDetail").Tables[0].NewRow();
                dgvRow.Cells[(int)DtlCol.RowSeqNo].Value = dgvRow.Index + 1;
                BaseFunctions.FillDataRowByGridRow(dgvRow, drBOM);
                drBOM["CategoryID"] = txtCategoryID.Text;
                drBOM["SetID"] = txtSetID.Text;
                drBOM["ProductFItemID"] = CvtFunc.ToInt ( txtProductFItemID.Text);
                if (rmBRL.UpdateDetailValid(dbcon, drBOM))
                {
                    dbcon.CommitTran();
                }
                else
                {
                    dbcon.RollbackTran();
                }

                dgvRow.Cells[(int)DtlCol.RecID].Value = CvtFunc.ToString(drBOM["RecID"]);
                dgvRow.Cells[(int)DtlCol.Qty].Value =  BaseFunctions.FormatNumeric( CvtFunc.ToDouble  ( drBOM["Qty"]).ToString ("f8")  ,"Ns.8");  
                dgvRow.Cells[(int)DtlCol.DetailCost].Value = BaseFunctions.FormatNumeric(drBOM["DetailCost"], "Ns.4");
                dgvRow.Cells[(int)DtlCol.TotalCost].Value = BaseFunctions.FormatNumeric(drBOM["TotalCost"], "Ns.4");
                dgvRow.Cells[(int)DtlCol.ValueChanged].Value = "0";
                dgvBOM.EndEdit();
                this.TimeStamp = (byte[])dbcon.GetObjectValue("Select RecStamp From " + this.TableName + " Where Recid=" + m_lRecId);
                FillHdrData(txtCategoryID.Text, txtSetID.Text, txtProductFItemID.Text,txtTechnicsName.Text );
            }
            catch (Exception ex)
            {
                MsgBoxEx.Show(ex.ToString());
                dbcon.RollbackTran();
                return false;
            }
            dbcon.CloseCon();
            return true;
        }
        private bool Update_Detail_LabourCost(DataGridViewRow dgvRow)
        {
            if (this.formStatus == FormStatus.Query) return true;
            if (dgvRow == null) return false;
            if (this.dgvLabourCost.ReadOnly) return true;
            this.dgvLabourCost.EndEdit();
            string strSQL = string.Empty;
            DBAccess dbcon = new DBAccess(false, false);
            try
            {
                if (txtSetID.Text == "" || txtCategoryID.Text == "") return true ; 
                dbcon.BeginTran();
                RMProductBOMHdrBRL rmBRL = new RMProductBOMHdrBRL();
                DataRow drLabourCost = dbcon.GetDataSet("select top 0 * from rmProductBOMLabourCost").Tables[0].NewRow();
                dgvRow.Cells[(int)LabourCostCol.RowSeqNo].Value = dgvRow.Index + 1;
                BaseFunctions.FillDataRowByGridRow(dgvRow, drLabourCost);
                drLabourCost["CategoryID"] = txtCategoryID.Text;
                drLabourCost["SetID"] = txtSetID.Text;
                drLabourCost["ProductFItemID"] =CvtFunc.ToInt ( txtProductFItemID.Text );
                if (rmBRL.UpdateDetailValid_LabourCost(dbcon, drLabourCost))
                {
                    dbcon.CommitTran();
                }
                else
                {
                    dbcon.RollbackTran();
                }

                dgvRow.Cells[(int)LabourCostCol.RecID].Value = CvtFunc.ToString(drLabourCost["RecID"]);
                dgvRow.Cells[(int)LabourCostCol.TotalQty].Value = BaseFunctions.FormatNumeric(drLabourCost["TotalQty"], "Ns.2");
                dgvRow.Cells[(int)LabourCostCol.UnitCost].Value = BaseFunctions.FormatNumeric(drLabourCost["UnitCost"], "Ns.6");
                dgvRow.Cells[(int)LabourCostCol.TotUnitCost].Value = BaseFunctions.FormatNumeric(drLabourCost["TotUnitCost"], "Ns.4");
                dgvRow.Cells[(int)LabourCostCol.UsedHours].Value = BaseFunctions.FormatNumeric(drLabourCost["SpendHours"], "Ns.6");
                dgvRow.Cells[(int)LabourCostCol.DtlLaborTotCost].Value = BaseFunctions.FormatNumeric(drLabourCost["DetailCost"], "Ns.4");
                dgvRow.Cells[(int)LabourCostCol.TotWorkCost].Value = BaseFunctions.FormatNumeric(drLabourCost["DetailTotWorkCost"], "Ns.2");
                dgvRow.Cells[(int)LabourCostCol.ValueChanged].Value = "0";
                this.TimeStamp = (byte[])dbcon.GetObjectValue("Select RecStamp From " + this.TableName + " Where Recid=" + m_lRecId);
                dgvLabourCost.EndEdit();
                FillHdrData( txtCategoryID.Text , txtSetID.Text,txtProductFItemID.Text,txtTechnicsName.Text  );
            }
            catch (Exception ex)
            {
                dbcon.RollbackTran();
                return false;
            }
            dbcon.CloseCon();
            return true;
        }

        public override bool DeleteData()
        {
            try
            {
                if (MessageBox.Show("您确实要删除此条信息？", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    mdbcon.BeginTran();
                    string strSQL = "Select * from rmProductBOMHdr where  CategoryID='{0}' and SetID='{1}' and ProductFItemID='{2}' and TechnicsName='{3}'";
                    strSQL = string.Format(strSQL, txtCategoryID.Text, txtSetID.Text, txtProductFItemID.Text,txtTechnicsName.Text );
                    DataRow drHdr = mdbcon.GetDataFirstRow(strSQL);
                    if (drHdr != null)
                    {
                        strSQL = " delete dbo.rmProductBOMDetail where  CategoryID='{0}' and SetID='{1}' and ProductFItemID='{2}' and TechnicsName='{3}' ";
                        strSQL = string.Format(strSQL, txtCategoryID.Text, txtSetID.Text, txtProductFItemID.Text, txtTechnicsName.Text);
                        mdbcon.ExecuteSql(strSQL);

                        strSQL = " delete dbo.rmProductBOMLabourCost where  CategoryID='{0}' and SetID='{1}' and ProductFItemID='{2}' and TechnicsName='{3}'";
                        strSQL = string.Format(strSQL, txtCategoryID.Text, txtSetID.Text, txtProductFItemID.Text, txtTechnicsName.Text);
                        mdbcon.ExecuteSql(strSQL);

                        strSQL = "delete dbo.rmWKProductFormula where BOMRecID in ( select RecID from rmProductBOMHdr where ProductFItemID ='{0}' and TechnicsName='{1}')";
                        strSQL = string.Format(strSQL, txtProductFItemID.Text, txtTechnicsName.Text);
                        mdbcon.ExecuteSql(strSQL);

                        strSQL = " delete dbo.rmWKFormulaOtherProductBOM where BOMRecID in ( select RecID from rmProductBOMHdr where ProductFItemID ='{0}' and TechnicsName='{1}')";
                        strSQL = string.Format(strSQL, txtProductFItemID.Text, txtTechnicsName.Text);
                        mdbcon.ExecuteSql(strSQL);

                        strSQL = " delete dbo.rmProductBOMHdr where CategoryID='{0}' and SetID='{1}' and ProductFItemID='{2}'  and TechnicsName='{3}'";
                        strSQL = string.Format(strSQL, txtCategoryID.Text, txtSetID.Text, txtProductFItemID.Text, txtTechnicsName.Text);
                        mdbcon.ExecuteSql(strSQL);

                        strSQL = " delete rmProductBOMSemi where CategoryID='{0}' and SetID='{1}' and ProductFItemID='{2}'  and TechnicsName='{3}'";
                        strSQL = string.Format(strSQL, txtCategoryID.Text, txtSetID.Text, txtProductFItemID.Text, txtTechnicsName.Text);
                        mdbcon.ExecuteSql(strSQL);
                    }
                    mdbcon.CommitTran();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                mdbcon.RollbackTran();
                return false;
            }
            

            if (true)
            {
                this.formStatus = FormStatus.Delete;
                this.RecID = -1;
                this.formStatus = FormStatus.Delete;
            }

            return true;
        }

        private bool Delete_Detail(DataGridViewRow dgvRow)
        {
            if (dgvRow == null) return false;
            string strSQL = string.Empty;
            RMProductBOMHdrBRL rmBRL = new RMProductBOMHdrBRL();
            DBAccess dbcon = new DBAccess ( false, false );
            string strRecID= CvtFunc.ToString ( dgvRow.Cells[(int)DtlCol.RecID].Value );
            if (rmBRL.DeleteDetailValid(dbcon, strRecID))
            {
                RMProductBOMHdrDAL rmDAL = new RMProductBOMHdrDAL();
                rmDAL.DeleteDetailBOM(dbcon, strRecID);
            }
            return true;
        }

        private bool Delete_Detail_LabourCost(DataGridViewRow dgvRow)
        {
            if (dgvRow == null) return false;
            string strSQL = string.Empty;
            RMProductBOMHdrBRL rmBRL = new RMProductBOMHdrBRL();
            DBAccess dbcon = new DBAccess(false, false);
            string strRecID = CvtFunc.ToString(dgvRow.Cells[(int)LabourCostCol.RecID].Value);
            if (rmBRL.DeleteDetailValid_LabourCost(dbcon, strRecID))
            {
                RMProductBOMHdrDAL rmDAL = new RMProductBOMHdrDAL();
                rmDAL.DeleteDetail_LabourCost(dbcon, strRecID);
            }
            return true;
        }

        private void FillDtl(string strCategoryID, string strSetID, string strProductFItemID, string strTechnicsName)
        {
            //InitBOMHdr();
            string strSql = "";
            string strUserName = "";
            string strRecid = "";
            bool bAccess = false;
            m_bCanTrigerCellValueChangedEven = false;

            this.dgvBOM.Rows.Clear();
            DBAccess dbCon = new DBAccess(false, false);
            
            string strProductName = DataFunctions.GetFieldValue(dbCon, "rmProduct", "ProductName", "ProductFItemID='" + strProductFItemID + "'");
            string strCategoryName = DataFunctions.GetFieldValue(dbCon, "rmCategory", "CategoryName", "CategoryID='" + strCategoryID + "'");
            string strSetName = DataFunctions.GetFieldValue(dbCon, "rmSet", "SetName", "SetID='" + strSetID + "'");

            strSql = "select A.* from rmProductBOMDetail A  where A.CategoryID='{0}' and A.SetID='{1}' and A.ProductFItemID='{2}' and A.TechnicsName='{3}' order by A.RowSeqNo,A.SeqNo";
            strSql = string.Format(strSql, strCategoryID, strSetID, strProductFItemID, strTechnicsName);
            DataTable mUserAlertTable = dbCon.GetDataSet(strSql).Tables[0];
            for (int i = 0; i < mUserAlertTable.Rows.Count; i++)
            {
                DataRow dr = mUserAlertTable.Rows[i];
                if (this.dgvBOM.Rows.Count <= i) this.dgvBOM.Rows.Add();
                dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.RowSeqNo].Value = dgvBOM.Rows.Count.ToString();
                dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.SeqNo].Value = dr["SeqNo"].ToString().TrimEnd();
                dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.WKID].Value = dr["WKID"].ToString().TrimEnd();
                dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.WKName].Value = DataFunctions.GetFieldValue (dbCon,"rmWorkingProcedure","WorkingProcedureName","WorkingProcedureID='"+ dr["WKID"] +"'")  ;
                
                dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.ProductFItemID].Value = dr["ProductFItemID"].ToString();
                dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.SetID].Value = dr["SetID"].ToString();
                dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.CategoryID].Value = dr["CategoryID"].ToString();

                dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.ProductName].Value =strProductName ;
                dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.TechnicsName].Value = dr["TechnicsName"].ToString().TrimEnd();
                dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.CategoryName].Value =strCategoryName ;
                dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.SetName].Value = strSetName ;
                dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.FItemID].Value = CvtFunc.ToString(dr["FItemID"]);

                strSql = "select ItemNo,ItemName from iminvmaster where FItemID='" + CvtFunc.ToString(dr["FItemID"]) + "'";
                DataRow drItemNo = mdbcon.GetDataFirstRow(strSql);
                if (drItemNo == null)
                {

                }
                else
                {
                    dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.ItemNo].Value = CvtFunc.ToString(drItemNo["ItemNo"]);
                    dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.ItemName].Value = CvtFunc.ToString(drItemNo["ItemName"]);
                }
                dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.LabourCost].Value = BaseFunctions.FormatNumeric(dr["LabourCost"], "Ns.4");
                dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.Price].Value = BaseFunctions.FormatNumeric(dr["Price"], "Ns.3");
                dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.PriceUnit].Value = CvtFunc.ToString(dr["PriceUnit"]);
                dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.PlanTreatCost].Value = BaseFunctions.FormatNumeric(dr["PlanTreatCost"], "Ns.3");
                
                dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.Qty].Value = BaseFunctions.FormatNumeric(CvtFunc.ToDouble(dr["Qty"]).ToString("F8"), "Ns.8");
                dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.QtyWastage].Value = BaseFunctions.FormatNumeric(dr["QtyWastage"], "Ns.2");
                dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.WastageRate].Value = BaseFunctions.FormatNumeric(dr["WastageRate"], "Ns.2");
                dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.TotalCost].Value = BaseFunctions.FormatNumeric(dr["TotalCost"], "Ns.4");
                dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.DetailCost].Value = BaseFunctions.FormatNumeric(dr["DetailCost"], "Ns.4");
                dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.IsKeyWK].Value = dr["IsKeyWK"].ToString();
                dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.IsInputWK].Value = dr["IsInputWK"].ToString();
                dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.SupNo].Value = dr["SupNo"].ToString();
                dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.SupName].Value = dr["SupName"].ToString();
                dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.RecID].Value = CvtFunc.ToInt(dr["RecID"]);
                dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.ValueChanged].Value = "0";
               
            }//
            this.dgvBOM.EndEdit();
            dbCon.CloseCon();
            base.SetBlankImage(dgvBOM);
            RefershRowSeqNo(this.dgvBOM.Name); 
            m_bCanTrigerCellValueChangedEven = true;
        }

        private void FillDtl_LabourCost(string strCategoryID, string strSetID, string strProductFItemID, string strTechnicsName)
        {
            string strSql = "";
            string strUserName = "";
            string strRecid = "";
            bool bAccess = false;
            m_bCanTrigerCellValueChangedEven_LabourCost = false;

            this.dgvLabourCost.Rows.Clear();
            DBAccess dbCon = new DBAccess(false, false);

            strSql = "select A.* from rmProductBOMLabourCost A  where A.CategoryID='" + strCategoryID + "' and A.SetID='" + strSetID + "' and A.ProductFItemID='" + strProductFItemID + "' and A.TechnicsName='" + strTechnicsName + "' order by A.RowSeqNo,A.seqno";
            DataTable mUserAlertTable = dbCon.GetDataSet(strSql).Tables[0];
            foreach (DataRow dr in mUserAlertTable.Rows)
            {
                this.dgvLabourCost.Rows.Add();
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.RowSeqNo].Value = dgvLabourCost.Rows.Count.ToString();
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.BOMSeqNo].Value = dr["BOMSeqNo"].ToString().TrimEnd();
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.SeqNo].Value = dr["SeqNo"].ToString().TrimEnd();
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.WKID].Value = dr["WKID"].ToString().TrimEnd();
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.WKName].Value = DataFunctions.GetFieldValue ( dbCon,"rmWorkingProcedure","WorkingProcedureName","WorkingProcedureID ='"+ dr["WKID"] +"'");
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.WKPriceType].Value = dr["WKPriceType"].ToString().TrimEnd();

                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.WKRemark].Value = dr["WKRemark"].ToString().TrimEnd();
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.IsKeyWK].Value = dr["IsKeyWK"].ToString().TrimEnd();
                
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.CategoryID].Value = dr["CategoryID"].ToString().TrimEnd();
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.SetID].Value = CvtFunc.ToString(dr["SetID"]);
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.ProductFItemID].Value = CvtFunc.ToString(dr["ProductFItemID"]);

                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.CategoryName].Value = DataFunctions.GetFieldValue(dbCon, "rmCategory", "CategoryName", " CategoryID='" + dr["CategoryID"] + "'");
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.SetName].Value = DataFunctions.GetFieldValue(dbCon, "rmSet", "SetName", " SetID='" + dr["SetID"] + "'");
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.ProductName].Value = DataFunctions.GetFieldValue(dbCon, "rmProduct", "ProductName", " ProductFItemID='" + dr["ProductFItemID"] + "'");
                
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.TechnicsName].Value = CvtFunc.ToString(dr["TechnicsName"]);
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.FItemID].Value = CvtFunc.ToString(dr["FItemID"]);
                strSql = "select ItemNo,ItemName from iminvmaster where FItemID='" + CvtFunc.ToString(dr["FItemID"]) + "'";
                DataRow drItemNo = mdbcon.GetDataFirstRow(strSql);
                if (drItemNo == null)
                {

                }
                else
                {
                    dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.ItemNo].Value = CvtFunc.ToString(drItemNo["ItemNo"]);
                    dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.ItemName].Value = CvtFunc.ToString(drItemNo["ItemName"]);
                }
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.WKOutName].Value = CvtFunc.ToString(dr["WKOutName"]);
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.CalUnit].Value = CvtFunc.ToString(dr["CalUnit"]);
                //dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.CutType].Value = CvtFunc.ToString(dr["CutType"]);
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.CutType].Value = (CvtFunc.ToString(dr["CutType"]) == "" ? "1" : CvtFunc.ToString(dr["CutType"]));
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.Remark].Value = CvtFunc.ToString(dr["Remark"]);
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.StandardQty].Value = BaseFunctions.FormatNumeric(dr["StandardQty"], "Ns.3");
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.StandardWage].Value = CvtFunc.ToString(dr["StandardWage"]);
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.StandardWage26].Value = BaseFunctions.FormatNumeric(dr["StandardWage26"], "Ns.2");
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.WorkQty].Value = BaseFunctions.FormatNumeric(dr["WorkQty"], "Ns.2");
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.TotalQty].Value = BaseFunctions.FormatNumeric(dr["TotalQty"], "Ns.2");
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.UnitCost].Value = BaseFunctions.FormatNumeric(dr["UnitCost"], "Ns.6");
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.TotUnitCost].Value = BaseFunctions.FormatNumeric(dr["TotUnitCost"], "Ns.4");
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.DtlLaborTotCost].Value = BaseFunctions.FormatNumeric(dr["DetailCost"], "Ns.4");
                

                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.WorkCost].Value = BaseFunctions.FormatNumeric(dr["WorkCost"], "Ns.4");
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.TotWorkCost].Value = BaseFunctions.FormatNumeric(dr["DetailTotWorkCost"], "Ns.2"); 
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.UsedHours].Value = BaseFunctions.FormatNumeric(dr["SpendHours"], "Ns.6");
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.RecID].Value = CvtFunc.ToInt(dr["RecID"]);
                dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.ValueChanged].Value = "0";
            }

            if (dgvLabourCost.Rows.Count == 0)
            {
                AddDtlRow(this.dgvLabourCost.Name);
            }
            dbCon.CloseCon();
            base.SetBlankImage(dgvLabourCost);
            m_bCanTrigerCellValueChangedEven_LabourCost = true;
        }

        private void ShowLabourCost()
        {
            InitGridDtlLabourCost();
            FillDtl_LabourCost(txtCategoryID.Text, txtSetID.Text, txtProductFItemID.Text,txtTechnicsName.Text );
        }

        private void ShowSemiProduct()
        {
            InitGridSemiProductDtl(this.dgvSemiProduct);
            InitGridSemiProductDtl(this.dgvSubSemiProduct);
            FillSemi();  
        }

        private void dgvBOM_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

            if (dgvBOM.Columns[e.ColumnIndex] is TextLookUpColumn)
            {
                if ((dgvBOM.Columns[e.ColumnIndex] as TextLookUpColumn).CanLookUp())
                {
                    Dtl_LookUp(e.ColumnIndex,this.dgvBOM.Name  );
                }
            }
            else
            {
                if (this.dgvBOM.CurrentCell.ColumnIndex == (int)DtlCol.DelButton && (this.formStatus == FormStatus.Update) && base.HasDelImage(this.dgvBOM, e))
                {
                    this.dgvBOM.CurrentCell.Selected = true;
                    this.dgvBOM.CurrentCell.Selected = false;
                    if (!this.Delete_Detail(this.dgvBOM.Rows[this.dgvBOM.CurrentCell.RowIndex]))
                    {
                        return;
                    }
                    this.dgvBOM.Rows.Remove(this.dgvBOM.Rows[this.dgvBOM.CurrentCell.RowIndex]);
                    if (this.dgvBOM.Rows.Count == 0)
                    {
                        this.AddDtlRow(this.dgvBOM.Name);
                    }
                }
            }
        }

        private void dgvLabourCost_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

            if (dgvLabourCost.Columns[e.ColumnIndex] is TextLookUpColumn)
            {
                if ((dgvLabourCost.Columns[e.ColumnIndex] as TextLookUpColumn).CanLookUp())
                {
                    Dtl_LookUp(e.ColumnIndex, this.dgvLabourCost.Name  );
                }
            }
            else
            {
                if (this.dgvLabourCost.CurrentCell.ColumnIndex == (int)LabourCostCol.DelButton && (this.formStatus == FormStatus.Update) && base.HasDelImage(this.dgvLabourCost, e))
                {
                    this.dgvLabourCost.CurrentCell.Selected = true;
                    this.dgvLabourCost.CurrentCell.Selected = false;
                    if (!this.Delete_Detail_LabourCost(this.dgvLabourCost.Rows[this.dgvLabourCost.CurrentCell.RowIndex]))
                    {
                        return;
                    }
                    this.dgvLabourCost.Rows.Remove(this.dgvLabourCost.Rows[this.dgvLabourCost.CurrentCell.RowIndex]);
                    if (this.dgvLabourCost.Rows.Count == 0)
                    {
                        this.AddDtlRow(this.dgvLabourCost.Name);
                    }
                }
            }
        }

        private void 可更改工序ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string strSQL = "", strCaption = "", strFindValue = "", strFindField = "", strWKName = "", strGridName = "", strWKID = ""; ;
            int intCol = 0;

            if (this.tbcMain.SelectedTab == tbpBOM)
                strWKID = CvtFunc.ToString(this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKID].Value );
            else
                strWKID = CvtFunc.ToString(this.dgvLabourCost.CurrentRow.Cells[(int)DtlCol.WKID].Value ); 
            
            strSQL = " select A.CategoryID as 类别编码, A.CategoryName as 类别名称,A.WKProductID as 工序编码,A.WKName as 工序名称,A.RecID from rmCategoryWKAlter A inner join rmCategoryWK B on a.hdrseqno=b.seqno where B.CategoryID='" + txtCategoryID.Text + "' and B.WKProductID='" + strWKID + "' ";
            strCaption = "工序选择";


            if (this.tbcMain.SelectedTab == tbpBOM)
                strGridName = this.dgvBOM.Name;
            else
                strGridName = this.dgvLabourCost.Name;

            if (strGridName == this.dgvBOM.Name)
            {
                intCol = this.dgvBOM.CurrentCell.ColumnIndex;
                strWKName = CvtFunc.ToString(this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKName].Value);
                if (this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKName].Value != null)
                    strFindValue = this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKName].Value.ToString();
            }
            else
            {
                intCol = this.dgvLabourCost.CurrentCell.ColumnIndex;
                strWKName = CvtFunc.ToString(this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKName].Value);
                if (this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKName].Value != null)
                    strFindValue = this.dgvBOM.CurrentRow.Cells[(int)LabourCostCol.WKName].Value.ToString();
            }
            strFindField = "WkName";
            DtlLookup(intCol, strSQL, strCaption, strFindValue, strFindField, "可更改工序ToolStripMenuItem", strGridName);
        }

        private void 所有工序ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string strSQL = "", strCaption = "", strFindValue = "", strFindField = "", strWKName = "", strGridName = "";
            int intCol = 0;
            strSQL = WP.Commons.BaseFunctions.GetLookUpSQL("rmWorkingProcedure");
            strSQL = BaseFunctions.GetSqlParts(strSQL, SqlOption.SqlPartMain) + " where GYUsed=1 " + BaseFunctions.GetSqlParts(strSQL, SqlOption.SqlPartOrderBy);
            strCaption = "工序选择";


            if (this.tbcMain.SelectedTab == tbpBOM)
                strGridName = this.dgvBOM.Name;
            else
                strGridName= this.dgvLabourCost.Name;

            if (strGridName == this.dgvBOM.Name)
            {
                intCol = this.dgvBOM.CurrentCell.ColumnIndex;
                strWKName = CvtFunc.ToString(this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKName].Value);
                if (this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKName].Value != null)
                    strFindValue = this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKName].Value.ToString();
            }
            else
            {
                intCol = this.dgvLabourCost.CurrentCell.ColumnIndex;
                strWKName = CvtFunc.ToString(this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKName].Value);
                if (this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKName].Value != null)
                    strFindValue = this.dgvBOM.CurrentRow.Cells[(int)LabourCostCol.WKName].Value.ToString();
            }
            strFindField = "WorkingProcedureName";
            DtlLookup(intCol, strSQL, strCaption, strFindValue, strFindField, "所有工序ToolStripMenuItem", strGridName);
        }

        private void 类别工序ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string strSQL = "", strCaption = "", strFindValue = "", strFindField = "", strWKName = "", strGridName = "";
            int intCol = 0;
            strSQL = "select RecID, WKProductID as 工序编码,WKName as 工序名称 from rmCategoryWK where categoryID='" + txtCategoryID.Text + "' order by WKName";
            strCaption = "类别工序选择";
            strCaption = "工序选择";


            if (this.tbcMain.SelectedTab == tbpBOM)
                strGridName = this.dgvBOM.Name;
            else
                strGridName = this.dgvLabourCost.Name;

            if (strGridName == this.dgvBOM.Name)
            {
                intCol = this.dgvBOM.CurrentCell.ColumnIndex;
                strWKName = CvtFunc.ToString(this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKName].Value);
                if (this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKName].Value != null)
                    strFindValue = this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKName].Value.ToString();
            }
            else
            {
                intCol = this.dgvLabourCost.CurrentCell.ColumnIndex;
                strWKName = CvtFunc.ToString(this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKName].Value);
                if (this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKName].Value != null)
                    strFindValue = this.dgvBOM.CurrentRow.Cells[(int)LabourCostCol.WKName].Value.ToString();
            }
            strFindField = "WkName";
            DtlLookup(intCol, strSQL, strCaption, strFindValue, strFindField, "类别工序ToolStripMenuItem", strGridName);
        }

        private void Dtl_LookUp(int iColumnIndex,string strGridName)
        {
            string strSQL = "", strCaption = "", strFindValue = "", strFindField = "";
            if (strGridName == this.dgvBOM.Name)
            {
                switch ((DtlCol)iColumnIndex)
                {
                    case DtlCol.WKName:
                        cmsWKLookup.Show(this.ActiveControl, new Point(this.ActiveControl.Top, this.ActiveControl.Left));
                        break;                        
                    case DtlCol.ItemNo:
                        strSQL = BaseFunctions.GetLookUpSQL("iminvmaster"); //" select ItemNo,ItemName,SupNo,SupName,MarketCost,CostUnit from iminvmaster where ClosedStatus=0 order by itemno";
                        strCaption = "物料选择";
                        if (this.dgvBOM.CurrentRow.Cells[(int)DtlCol.ItemNo].Value != null) strFindValue = this.dgvBOM.CurrentRow.Cells[(int)DtlCol.ItemNo].Value.ToString();
                        strFindField = "ItemNo";
                        break;
                }
            }
            else if (strGridName == this.dgvLabourCost.Name)
            {
                switch ((LabourCostCol)iColumnIndex)
                {
                    case LabourCostCol.WKName:

                        //cmsWKLookup.Show(this.ActiveControl, new Point(this.ActiveControl.Top, this.ActiveControl.Left));
                        strSQL = "select RecID,CategoryID as 类别编码,CategoryName as 类别名称,WKProductID as 工序编码,WKName as 工序名称,WKPriceType as 工价类别,WKSalary as 固定工资,WKSTDSalary as 标准工资,WorkCostRate as 工时费用标准,WKSTDQty as 额定产能,STDQtyUnit as 单位 from imCategoryWKWorkCost where WKProductID in ( select WorkingProcedureID from rmWorkingProcedure where FianUsed=1) and CategoryID='" + txtCategoryID.Text + "'";                        
                        break;       

                    case LabourCostCol.CalUnit:
                        strSQL = WP.Commons.BaseFunctions.GetLookUpSQL("imUnit");
                        strCaption = "";
                        if (this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.CalUnit].Value != null) strFindValue = this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.CalUnit].Value.ToString();
                        strFindField = "Unit";
                        
                        break;
                    case LabourCostCol.CutType:
                        strSQL = WP.Commons.BaseFunctions.GetLookUpSQL("rmCutType");
                        strCaption = "分切方式选择";
                        if (this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.CutType].Value != null) strFindValue = this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.CutType].Value.ToString();
                        strFindField = "CutTimes";                                           
                        break;

                    case LabourCostCol.ItemNo:
                        strSQL = BaseFunctions.GetLookUpSQL ("iminvmaster") ;//" select ItemNo,ItemName,SupNo,SupName,MarketCost,CostUnit from iminvmaster where ClosedStatus=0 order by itemno";
                        strCaption = "物料选择";
                        if (this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.ItemNo].Value != null) strFindValue = this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.ItemNo].Value.ToString();
                        strFindField = "ItemNo";
                        break;
                }
            }
            else if (strGridName == this.dgvSemiBOM.Name)
            {
                if (iColumnIndex == this.dgvSemiBOM.Columns["ParentSemiCode"].Index)
                {
                    string strSemiCode = "", strSemiName = "",strSemiRecID="";
                    if (GetCurSemiCode(ref strSemiRecID, ref strSemiCode, ref strSemiName))
                    {
                        string strRecID = CvtFunc.ToString(this.dgvSemiBOM.Rows[0].Cells["RecID"].Value);
                        strSQL = @"Select SemiCode,SemiName,Quantity,Unit,WorkCost,LabourCost,BOMCost,SemiTotalCost FROM rmProductBOMSemi where RecID='{0}'
                              And CategoryID='{1}' And SetID='{2}' And ProductFItemID='{3}' And TechnicsName='{4}'  ";
                        strSQL = string.Format(strSQL, strRecID, txtCategoryID.Text, txtSetID.Text, txtTechnicsName.Text);
                    }
                }
            }
            else if (strGridName == this.dgvSemiProduct.Name)
            {
                if (iColumnIndex == this.dgvSemiProduct.Columns["SemiCode"].Index)
                {
                    strSQL = "select * from imSemiProduct order by SemiCode";
                }
            }
            if (strSQL == "") return;
            if (mblnLookUpSortByDescription)
            {
                strSQL = DataFunctions.GetSqlByDescriptionSort(strSQL);
                mblnLookUpSortByDescription = false;
            }

            DtlLookup(iColumnIndex, strSQL, strCaption, strFindValue, strFindField,"", strGridName);
        }

       

        private void DtlLookup(int iColumnIndex, string strSQL, string strCaption, string strFindValue, string strFindField, string strMenuName, string strGridName)
        {

            frmLookUp frmlookup = null;
            frmLookUpItem frmlookupitem =  null ;
            bool blnHaveReturnValue = false;
            if ((DtlCol)iColumnIndex == DtlCol.ItemNo)
            {
                frmlookupitem = new frmLookUpItem(strSQL, strCaption, strFindValue, strFindField);
                frmlookupitem.ShowDialog();
                blnHaveReturnValue = frmlookupitem.HaveReturnValue;
            }
            else
            {
                frmlookup = new frmLookUp(strSQL, strCaption, strFindValue, strFindField);            
                frmlookup.ShowDialog();
                blnHaveReturnValue = frmlookup.HaveReturnValue;
            }

            if (blnHaveReturnValue)
            {
                if (strGridName == this.dgvBOM.Name)
                {
                    switch ((DtlCol)iColumnIndex)
                    {
                        case DtlCol.WKName:
                            if (strMenuName == this.可更改工序ToolStripMenuItem.Name)
                            {
                                this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKID].Value = frmlookup.GetReturnValue("WKProductID");
                                this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKName].Value = frmlookup.GetReturnValue("WkName");
                                //this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKRemark].Value = frmlookup.GetReturnValue("Remark");
                            }
                            else if (strMenuName == this.类别工序ToolStripMenuItem.Name)
                            {
                                this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKID].Value = frmlookup.GetReturnValue("WKProductID");
                                this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKName].Value = frmlookup.GetReturnValue("WKName");
                            }
                            else if (strMenuName == this.所有工序ToolStripMenuItem.Name)
                            {
                                this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKID].Value = frmlookup.GetReturnValue("WorkingProcedureID");
                                this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKName].Value = frmlookup.GetReturnValue("WorkingProcedureName");
                                this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKRemark].Value = frmlookup.GetReturnValue("Remark");
                            }                            
                            break;
                        case DtlCol.ItemNo:
                            this.dgvBOM.CurrentRow.Cells[(int)DtlCol.FItemID].Value = frmlookupitem.GetReturnValue("FItemID");
                            this.dgvBOM.CurrentRow.Cells[(int)DtlCol.ItemNo].Value = frmlookupitem.GetReturnValue("ItemNo");
                            this.dgvBOM.CurrentRow.Cells[(int)DtlCol.ItemName].Value = frmlookupitem.GetReturnValue("ItemName");
                            this.dgvBOM.CurrentRow.Cells[(int)DtlCol.SupNo].Value = frmlookupitem.GetReturnValue("SupNo");
                            this.dgvBOM.CurrentRow.Cells[(int)DtlCol.SupName].Value = frmlookupitem.GetReturnValue("SupName");
                            this.dgvBOM.CurrentRow.Cells[(int)DtlCol.Price].Value = frmlookupitem.GetReturnValue("MarketCost");
                            this.dgvBOM.CurrentRow.Cells[(int)DtlCol.PriceUnit].Value = frmlookupitem.GetReturnValue("CostUnit");
                            break;
                    }
                }
                else if (strGridName == this.dgvLabourCost.Name)
                {
                    switch ((LabourCostCol)iColumnIndex)
                    {
                        case LabourCostCol.WKName:
                            if (strMenuName == this.可更改工序ToolStripMenuItem.Name)
                            {
                                this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKID].Value = frmlookup.GetReturnValue("WkID");
                                this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKName].Value = frmlookup.GetReturnValue("WkName");
                                //this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKRemark].Value = frmlookup.GetReturnValue("Remark");
                            }
                            else if (strMenuName == this.类别工序ToolStripMenuItem.Name)
                            {
                                this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKID].Value = frmlookup.GetReturnValue("WKProductID");
                                this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKName].Value = frmlookup.GetReturnValue("WKName");
                            }
                            else if (strMenuName == this.所有工序ToolStripMenuItem.Name)
                            {
                                this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKID].Value = frmlookup.GetReturnValue("WorkingProcedureID");
                                this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKName].Value = frmlookup.GetReturnValue("WorkingProcedureName");
                                this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKRemark].Value = frmlookup.GetReturnValue("Remark");
                            }
                            else
                            {
                                this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKID].Value = frmlookup.GetReturnValue("WKProductID");
                                this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKName].Value = frmlookup.GetReturnValue("WKName");
                                this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKPriceType].Value = frmlookup.GetReturnValue("WKPriceType");
                                this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.CalUnit].Value = frmlookup.GetReturnValue("STDQtyUnit");
                                this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKRemark].Value = DataFunctions.GetFieldValue("rmWorkingProcedure", "Remark", "WorkingProcedureID='" + CvtFunc.ToString(this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKID].Value) + "'"); 
                            }
                            break;
                        case LabourCostCol.CalUnit:
                            this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.CalUnit].Value = frmlookup.GetReturnValue("Unit");
                            break;
                        case LabourCostCol.CutType:
                            this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.CutType].Value = frmlookup.GetReturnValue(strFindField);
                            break;
                        case LabourCostCol.ItemNo:
                            {
                                this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.FItemID].Value = frmlookup.GetReturnValue("FItemID");
                                this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.ItemNo].Value = frmlookup.GetReturnValue("ItemNo");
                            }
                            break;
                    }
                }
                else if (strGridName == this.dgvSemiProduct.Name)
                {
                    if (iColumnIndex == this.dgvSemiProduct.Columns["SemiCode"].Index)
                    {
                        this.dgvSemiProduct.CurrentRow.Cells["SemiCode"].Value = frmlookup.GetReturnValue("SemiCode");
                        this.dgvSemiProduct.CurrentRow.Cells["SemiName"].Value = frmlookup.GetReturnValue("SemiName");
                        this.dgvSemiProduct.CurrentRow.Cells["Unit"].Value = frmlookup.GetReturnValue("Unit");
                    }
                }
            }
            if (frmlookupitem != null)
            {
                frmlookupitem.Close();
            }
            else
            {
                frmlookup.Close();
            }
        }


        private void dgvBOM_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            if (dgvBOM.CurrentRow == null)
            {
                e.Cancel = false;
                return;
            }
            if (int.Parse(dgvBOM.CurrentRow.Cells[(int)DtlCol.RecID].Value.ToString()) > 0 && int.Parse(dgvBOM.CurrentRow.Cells[(int)DtlCol.ValueChanged].Value.ToString()) == 0)
            {
                e.Cancel = false;
                return;

            }

            if (mhtiDtl != null && mhtiDtl.ColumnIndex == (int)DtlCol.DelButton)
            {
                mhtiDtl = null;
                return;
            }


            if (this.dgvBOM.CurrentCell.ColumnIndex == (int)DtlCol.DelButton)
            {
                e.Cancel = false;
                return;

            }
            string strErrMsg = "";
            if (!BaseFunctions.NeedValidGridCell(this.ActiveControl, "dgvBOM") || m_bSettingStatus || !m_bCanTrigerCellValueChangedEven)
            {
                e.Cancel = false;
                return;
            }

            e.Cancel = !CheckDtlCell(e.ColumnIndex, ref strErrMsg);
            if (strErrMsg != "")
            {
                MessageBox.Show(strErrMsg, SysVar.WarnTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }

        private void dgvBOM_RowValidating(object sender, DataGridViewCellCancelEventArgs e)
        {
            if (dgvBOM.CurrentRow != null && int.Parse(dgvBOM.CurrentRow.Cells[(int)DtlCol.RecID].Value.ToString()) > 0 && int.Parse(dgvBOM.CurrentRow.Cells[(int)DtlCol.ValueChanged].Value.ToString()) == 0)
            {
                e.Cancel = false;
                return;

            }

            string strErrMsg = "";
            if (!BaseFunctions.NeedValidGridCell(this.ActiveControl, "dgvBOM") || m_bSettingStatus || !m_bCanTrigerCellValueChangedEven)
            {
                e.Cancel = false;
                return;
            }
            e.Cancel = !CheckDtlRow(ref strErrMsg);
            if (strErrMsg != "")
            {
                MessageBox.Show(strErrMsg, SysVar.WarnTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }

        }

        private void dgvBOM_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (!m_bCanTrigerCellValueChangedEven || e.ColumnIndex == (int)DtlCol.ValueChanged || e.ColumnIndex == (int)DtlCol.DelButton) return;
            dgvBOM.Rows[e.RowIndex].Cells[(int)DtlCol.ValueChanged].Value = "1";
            m_bDtlChanged = true;
            dgvBOM.EndEdit();
            if (e.ColumnIndex == (int)DtlCol.WKID)
            {
                string strWKID = CvtFunc.ToString(this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKID].Value);
                this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKName].Value = DataFunctions.GetFieldValue("rmWorkingProcedure", "WorkingProcedureName", "WorkingProcedureID='" + strWKID + "'");
                this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKRemark].Value = DataFunctions.GetFieldValue("rmWorkingProcedure", "Remark", "WorkingProcedureID='" + strWKID + "'");
            }
            if (e.ColumnIndex == (int)DtlCol.WKName)
            {
                this.dgvBOM.CurrentRow.Cells[(int)DtlCol.IsKeyWK].Value = DataFunctions.GetFieldValue("rmCategoryWK", "IsKeyWK", "CategoryID='" + txtCategoryID.Text + "' and WKProductID='" + CvtFunc.ToString(this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKID].Value) + "'");
                if (CvtFunc.ToString(this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKID].Value) == "")
                {
                    this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKID].Value = DataFunctions.GetFieldValue("rmWorkingProcedure", "WorkingProcedureID", "WorkingProcedureName='" + CvtFunc.ToString(this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKName].Value) + "'");
                }
            }
            if (e.ColumnIndex == (int)DtlCol.ItemNo)
            {
                if (DataFunctions.GetFieldValue("imInvMaster", "FItemID", "ItemNo='" + CvtFunc.ToString(this.dgvBOM.CurrentRow.Cells[(int)DtlCol.ItemNo].Value) + "'") != "")
                {
                    this.dgvBOM.CurrentRow.Cells[(int)DtlCol.FItemID].Value = DataFunctions.GetFieldValue("imInvMaster", "FItemID", "ItemNo='" + CvtFunc.ToString(this.dgvBOM.CurrentRow.Cells[(int)DtlCol.ItemNo].Value) + "'");
                }
            }
            if (e.ColumnIndex == (int)DtlCol.FItemID)
            {
                string strFItemID = CvtFunc.ToString(this.dgvBOM.CurrentRow.Cells[(int)DtlCol.FItemID].Value);
                string strSQL = "select * from iminvmaster where FItemID='" + strFItemID + "'";
                DataRow drItemInfo = mdbcon.GetDataFirstRow(strSQL);
                if (drItemInfo != null)
                {
                    this.dgvBOM.CurrentRow.Cells[(int)DtlCol.ItemNo].Value = CvtFunc.ToString(drItemInfo["itemno"]);
                    this.dgvBOM.CurrentRow.Cells[(int)DtlCol.ItemName].Value = CvtFunc.ToString(drItemInfo["itemname"]);
                    this.dgvBOM.CurrentRow.Cells[(int)DtlCol.SupNo].Value = CvtFunc.ToString(drItemInfo["SupNo"]);
                    this.dgvBOM.CurrentRow.Cells[(int)DtlCol.SupName].Value = CvtFunc.ToString(drItemInfo["SupName"]);
                    this.dgvBOM.CurrentRow.Cells[(int)DtlCol.Price].Value = CvtFunc.ToString(drItemInfo["MarketCost"]);
                    this.dgvBOM.CurrentRow.Cells[(int)DtlCol.PriceUnit].Value = CvtFunc.ToString(drItemInfo["CostUnit"]);
                }
            }
            dgvBOM.EndEdit();
        }

        private void dgvBOM_CellEnter(object sender, DataGridViewCellEventArgs e)
        {
            if (this.dgvBOM.CurrentCell.ColumnIndex == (int)DtlCol.DelButton)
            {
                this.dgvBOM.CurrentCell.Selected = false;
            }
            if (this.dgvBOM.CurrentRow == null) return;
            ShowFormula(this.dgvBOM.CurrentRow.Index);
            ChangeGridSelectRowBackColor(dgvBOM);
        }

        private void ChangeGridSelectRowBackColor(DataGridView dgvView)
        {
            foreach (DataGridViewColumn dccol in dgvView.Columns)
            {
                for (int i = 0; i <= dgvView.Rows.Count - 1; i++)
                {
                    dgvView.Rows[i].Cells[dccol.Name].Style.BackColor = Color.White;
                }
            }
            foreach (DataGridViewColumn dccol in dgvView.Columns)
            {
                dgvView.CurrentRow.Cells[dccol.Name].Style.BackColor = Color.AntiqueWhite;
            }
        }

        private void dgvBOM_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (this.dgvBOM.CurrentCell.ColumnIndex == (int)DtlCol.DelButton)
            {
                this.dgvBOM.CurrentCell.Selected = false;
            }
        }

        private void dgvBOM_CellLeave(object sender, DataGridViewCellEventArgs e)
        {
            this.dgvBOM.EndEdit();

           
            if (e.ColumnIndex == (int)DtlCol.WKName)
            {
                this.dgvBOM.Rows[e.RowIndex].Cells[(int)DtlCol.IsKeyWK].Value = DataFunctions.GetFieldValue("rmCategoryWK", "IsKeyWK", "CategoryID='" + txtCategoryID.Text + "' and WKProductID='" + CvtFunc.ToString(this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKID].Value) + "'");
            }
            else if (e.ColumnIndex == (int)DtlCol.ItemNo)
            {
                if (CvtFunc.ToString(this.dgvBOM.Rows[e.RowIndex].Cells[(int)DtlCol.ItemNo].Value) == "")  // 可能手工删除了物料
                {
                    this.dgvBOM.Rows[e.RowIndex].Cells[(int)DtlCol.ItemName].Value = "";
                    this.dgvBOM.Rows[e.RowIndex].Cells[(int)DtlCol.FItemID].Value = "0";
                    this.dgvBOM.Rows[e.RowIndex].Cells[(int)DtlCol.PriceUnit].Value = "";
                }
            }
            else if (e.ColumnIndex == (int)DtlCol.Price)
            {
                this.dgvBOM.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = BaseFunctions.FormatNumeric(this.dgvBOM.Rows[e.RowIndex].Cells[e.ColumnIndex].Value, "Ns.3");
            }
            else if (e.ColumnIndex == (int)DtlCol.Qty)
            {
                this.dgvBOM.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = CvtFunc.ToDouble(this.dgvBOM.Rows[e.RowIndex].Cells[e.ColumnIndex].Value).ToString ("F8") ;
            }
            else if (e.ColumnIndex == (int)DtlCol.WastageRate)
            {
                this.dgvBOM.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = BaseFunctions.FormatNumeric(this.dgvBOM.Rows[e.RowIndex].Cells[e.ColumnIndex].Value, "Ns.2");
            }
            else if (e.ColumnIndex == (int)DtlCol.LabourCost)
            {
                this.dgvBOM.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = BaseFunctions.FormatNumeric(this.dgvBOM.Rows[e.RowIndex].Cells[e.ColumnIndex].Value, "Ns.4");
            }
            else if (e.ColumnIndex == (int)DtlCol.DetailCost)
            {
                this.dgvBOM.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = BaseFunctions.FormatNumeric(this.dgvBOM.Rows[e.RowIndex].Cells[e.ColumnIndex].Value, "Ns.4");
            }

            if (this.dgvBOM.Rows[e.RowIndex].Cells[(int)DtlCol.ValueChanged].Value == "1" && (e.ColumnIndex == (int)DtlCol.Price || e.ColumnIndex == (int)DtlCol.PriceUnit || e.ColumnIndex == (int)DtlCol.ItemNo
               || e.ColumnIndex == (int)DtlCol.Qty || e.ColumnIndex == (int)DtlCol.WastageRate || e.ColumnIndex == (int)DtlCol.LabourCost))
            {
                string strErrMsg = string.Empty;
                if (CheckDtlRow(ref strErrMsg))
                {
                    Update_Detail(this.dgvBOM.Rows[e.RowIndex]);
                }
            }
        }

        private void dgvBOM_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            return;
        }

        private void dgvBOM_RowEnter(object sender, DataGridViewCellEventArgs e)
        {
            base.SetGridViewDelImage(this.dgvBOM, e, (int)DtlCol.DelButton);
            //if (this.formStatus == FormStatus.Query)
            //{
            //    dgvBOM.Enabled = false;
            //    return;
            //}
            string strErrMsg = "";
            if (dgvBOM.CurrentRow != null && CvtFunc.ToInt(dgvBOM.CurrentRow.Cells[(int)DtlCol.ValueChanged].Value) > 0)
            {
                if (CheckDtlRow(ref strErrMsg))
                {
                    if (!Update_Detail(this.dgvBOM.Rows[this.dgvBOM.CurrentCell.RowIndex]))
                    {
                        return;
                    }
                    //ShowLabourCost();
                }
                else
                {
                    return;
                }
            }
           
        }

        private void dgvBOM_MouseDown(object sender, MouseEventArgs e)
        {

            mhtiDtl = this.dgvBOM.HitTest(e.X, e.Y);

            //System.Windows.Forms.DataGridView.HitTestInfo hti;
            //hti = this.dgvBOM.HitTest(e.X, e.Y);
            //switch (hti.Type)
            //{
            //    case System.Windows.Forms.DataGridViewHitTestType.Cell:
            //        break;
            //}
        }

        private bool dgvBOM_KeyDownEvent(System.Windows.Forms.Keys keyData)
        {
            string strErrMsg = "";
            int j;
            switch (keyData)
            {
                case Keys.Down:
                    #region Key Down

                    this.dgvBOM.EndEdit();
                    if (CvtFunc.ToInt(dgvBOM.CurrentRow.Cells[(int)DtlCol.RecID].Value) > 0)
                    {
                        if (CvtFunc.ToInt(dgvBOM.CurrentRow.Cells[(int)DtlCol.ValueChanged].Value) > 0)
                        {

                            if (CheckDtlRow(ref strErrMsg))
                            {

                                if (!Update_Detail(this.dgvBOM.Rows[this.dgvBOM.CurrentCell.RowIndex]))
                                {
                                    return true;
                                }
                            }
                            else
                            {
                                MessageBox.Show(strErrMsg, SysVar.WarnTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                                return true;
                            }
                        }
                        if (dgvBOM.CurrentCell.RowIndex < dgvBOM.Rows.Count - 1)
                        {
                            dgvBOM.CurrentCell = this.dgvBOM.Rows[dgvBOM.CurrentCell.RowIndex + 1].Cells[(int)DtlCol.WKName];
                        }
                        else
                        {
                            if (this.formStatus == FormStatus.Update) AddDtlRow(this.dgvBOM.Name);
                        }
                    }
                    else
                    {
                        if (CheckDtlRow(ref strErrMsg))
                        {
                            if (!Update_Detail(this.dgvBOM.Rows[this.dgvBOM.CurrentCell.RowIndex]))
                            {
                                return true;
                            }
                            if (this.formStatus == FormStatus.Update) AddDtlRow(this.dgvBOM.Name);
                        }
                        else
                        {
                            MessageBox.Show(strErrMsg, SysVar.WarnTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                            return true;
                        }
                    }
                    return true;


                    #endregion
                case Keys.Up:
                    #region Key Up
                    if (CvtFunc.ToInt(dgvBOM.CurrentRow.Cells[(int)DtlCol.RecID].Value) > 0)
                    {
                        if (CvtFunc.ToInt(dgvBOM.CurrentRow.Cells[(int)DtlCol.ValueChanged].Value) > 0)
                        {
                            if (CheckDtlRow(ref strErrMsg))
                            {
                                if (!Update_Detail(this.dgvBOM.Rows[this.dgvBOM.CurrentCell.RowIndex])) return true;
                            }
                            else
                            {
                                MessageBox.Show(strErrMsg, SysVar.WarnTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                                return true;
                            }
                        }
                        if (dgvBOM.CurrentCell.RowIndex > 0)
                        {
                            dgvBOM.CurrentCell = this.dgvBOM.Rows[dgvBOM.CurrentCell.RowIndex - 1].Cells[(int)DtlCol.WKName];
                        }
                    }
                    else
                    {
                        if (CheckDtlRow(ref strErrMsg))
                        {
                            if (!Update_Detail(this.dgvBOM.Rows[this.dgvBOM.CurrentCell.RowIndex])) return true;
                            if (dgvBOM.CurrentCell.RowIndex > 0)
                            {
                                dgvBOM.CurrentCell = this.dgvBOM.Rows[dgvBOM.CurrentCell.RowIndex - 1].Cells[(int)DtlCol.WKName];
                            }
                        }
                        else if (dgvBOM.Rows.Count > 1)
                        {

                            this.dgvBOM.Rows.Remove(this.dgvBOM.CurrentRow);
                            dgvBOM.CurrentCell = this.dgvBOM.Rows[dgvBOM.Rows.Count - 1].Cells[(int)DtlCol.WKName];
                        }
                    }
                    return true;
                    #endregion
                case Keys.Enter:
                    #region Key Enter
                    this.dgvBOM.EndEdit();
                    j = BaseFunctions.GetGridViewLastEnabledEditColumn(this.dgvBOM);
                    if (dgvBOM.CurrentCell.ColumnIndex == j)
                    {
                        if (CvtFunc.ToInt(dgvBOM.CurrentRow.Cells[(int)DtlCol.RecID].Value) > 0)
                        {
                            if (CvtFunc.ToInt(dgvBOM.CurrentRow.Cells[(int)DtlCol.ValueChanged].Value) > 0)
                            {
                                if (CheckDtlRow(ref strErrMsg))
                                {
                                    if (!Update_Detail(this.dgvBOM.Rows[this.dgvBOM.CurrentCell.RowIndex])) return true;
                                }
                                else
                                {
                                    MessageBox.Show(strErrMsg, SysVar.WarnTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                                    return true;
                                }
                            }
                        }
                        else
                        {
                            if (CheckDtlRow(ref strErrMsg))
                            {
                                if (!Update_Detail(this.dgvBOM.Rows[this.dgvBOM.CurrentCell.RowIndex])) return true;
                            }
                            else
                            {
                                MessageBox.Show(strErrMsg, SysVar.WarnTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                                return true;
                            }

                        }
                        if (dgvBOM.CurrentCell.RowIndex < dgvBOM.Rows.Count - 1)
                        {
                            dgvBOM.CurrentCell = this.dgvBOM.Rows[dgvBOM.CurrentCell.RowIndex + 1].Cells[(int)DtlCol.WKName];
                        }
                        else
                        {
                            if (this.formStatus == FormStatus.Update) AddDtlRow(this.dgvBOM.Name);
                        }
                    }
                    else
                    {
                        j = BaseFunctions.GetGridViewNextEnabledEditColumn(dgvBOM, dgvBOM.CurrentCell.ColumnIndex);
                        if (j >= 0) SendKeys.Send("{Tab}");
                        //  if (j >= 0) dgvBOM.CurrentCell = this.dgvBOM.Rows[dgvBOM.CurrentCell.RowIndex].Cells[j];
                    }

                    return true;
                    #endregion
            }
            return false;
        }

        private void dgvBOM_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
        {
            // 对第1列相同单元格进行合并
            if (e.ColumnIndex ==(int)DtlCol.WKName && e.RowIndex != -1)
            {
                using
                    (
                    Brush gridBrush = new SolidBrush(this.dgvBOM.GridColor),
                    backColorBrush = new SolidBrush(e.CellStyle.BackColor)
                    )
                {
                    using (Pen gridLinePen = new Pen(gridBrush))
                    {
                        // 清除单元格
                        e.Graphics.FillRectangle(backColorBrush, e.CellBounds);

                        // 画 Grid 边线（仅画单元格的底边线和右边线）
                        //   如果下一行和当前行的数据不同，则在当前的单元格画一条底边线
                        if (e.RowIndex < dgvBOM.Rows.Count - 1 && dgvBOM.Rows[e.RowIndex + 1].Cells[e.ColumnIndex].Value.ToString() != e.Value.ToString())
                            e.Graphics.DrawLine(gridLinePen, e.CellBounds.Left, e.CellBounds.Bottom - 1, e.CellBounds.Right - 1, e.CellBounds.Bottom - 1);
                        // 画右边线
                        e.Graphics.DrawLine(gridLinePen, e.CellBounds.Right - 1, e.CellBounds.Top, e.CellBounds.Right - 1, e.CellBounds.Bottom);

                        // 画（填写）单元格内容，相同的内容的单元格只填写第一个
                        if (e.Value != null)
                        {
                            if (e.RowIndex > 0 && dgvBOM.Rows[e.RowIndex - 1].Cells[e.ColumnIndex].Value.ToString() == e.Value.ToString())
                            { }
                            else
                            {
                                e.Graphics.DrawString((String)e.Value, e.CellStyle.Font, Brushes.Black, e.CellBounds.X + 2, e.CellBounds.Y + 5, StringFormat.GenericDefault);
                            }
                        }
                        e.Handled = true;
                    }
                }
            }
        }

        #endregion


        #region LabourCost

        private void dgvLabourCost_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            if (dgvLabourCost.CurrentRow == null)
            {
                e.Cancel = false;
                return;
            }
            if (CvtFunc.ToInt(dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.RecID].Value) > 0 && CvtFunc.ToInt(dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.ValueChanged].Value) == 0)
            {
                e.Cancel = false;
                return;

            }

            if (mhtiDtl != null && mhtiDtl.ColumnIndex == (int)LabourCostCol.DelButton)
            {
                mhtiDtl = null;
                return;
            }


            if (this.dgvLabourCost.CurrentCell.ColumnIndex == (int)LabourCostCol.DelButton)
            {
                e.Cancel = false;
                return;

            }
            string strErrMsg = "";
            if (!BaseFunctions.NeedValidGridCell(this.ActiveControl, "dgvLabourCost") || m_bSettingStatus || !m_bCanTrigerCellValueChangedEven_LabourCost)
            {
                e.Cancel = false;
                return;
            }

            e.Cancel = !CheckDtlCell_LabourCost (e.ColumnIndex, ref strErrMsg);
            if (strErrMsg != "")
            {
                MessageBox.Show(strErrMsg, SysVar.WarnTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }

        private void dgvLabourCost_RowValidating(object sender, DataGridViewCellCancelEventArgs e)
        {
            if (dgvLabourCost.CurrentRow != null && CvtFunc.ToInt(dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.RecID].Value) > 0 && CvtFunc.ToInt(dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.ValueChanged].Value) == 0)
            {
                e.Cancel = false;
                return;

            }

            string strErrMsg = "";
            if (!BaseFunctions.NeedValidGridCell(this.ActiveControl, "dgvLabourCost") || m_bSettingStatus || !m_bCanTrigerCellValueChangedEven_LabourCost )
            {
                e.Cancel = false;
                return;
            }
            e.Cancel = !CheckDtlRow_LabourCost (ref strErrMsg);
            if (strErrMsg != "")
            {
                MessageBox.Show(strErrMsg, SysVar.WarnTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }

        }

        private void dgvLabourCost_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (!m_bCanTrigerCellValueChangedEven_LabourCost || e.ColumnIndex == (int)LabourCostCol.ValueChanged || e.ColumnIndex == (int)LabourCostCol.DelButton) return;
            dgvLabourCost.Rows[e.RowIndex].Cells[(int)LabourCostCol.ValueChanged].Value = "1";
            m_bDtlChanged_LabourCost  = true;
            dgvLabourCost.EndEdit();
            if (e.ColumnIndex == (int)LabourCostCol.WKID || e.ColumnIndex ==(int)LabourCostCol.WKPriceType)
            {
                string strWKID = CvtFunc.ToString(this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKID].Value);
                string strWKPriceType = CvtFunc.ToString(this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKPriceType].Value);
                this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKName].Value = DataFunctions.GetFieldValue("rmWorkingProcedure", "WorkingProcedureName", "WorkingProcedureID='" + strWKID + "'");
                this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKOutName].Value = DataFunctions.GetFieldValue("rmWorkingProcedure", "WKOut", "WorkingProcedureID='" + strWKID + "'");
                string strWKName =CvtFunc.ToString ( this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKName].Value);
                this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKRemark].Value = DataFunctions.GetFieldValue("rmWorkingProcedure", "Remark", "WorkingProcedureID='" + strWKID + "'");
                this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.IsKeyWK].Value = DataFunctions.GetFieldValue("rmCategoryWK", "IsKeyWK", "CategoryID='" + txtCategoryID.Text + "' and WKProductID='" + strWKID + "'");
                if (CvtFunc.ToDouble(this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.RecID].Value) <= 0)
                {
                    double dblWorkCost = DataFunctions.GetCategoryWKWorkCost(txtCategoryID.Text, strWKID, strWKPriceType);
                    if (dblWorkCost > 0)
                    {
                        this.dgvLabourCost.Rows[e.RowIndex].Cells[(int)LabourCostCol.WorkCost].Value = BaseFunctions.FormatNumeric(dblWorkCost, "Ns.2");
                    }
                }
                string strSQL = "select * from [imCategoryWKWorkCost] where CategoryID='{0}' and WKProductID='{1}' and WKPriceType='{2}'";
                strSQL = string.Format(strSQL, txtCategoryID.Text, strWKID, strWKPriceType);
                DBAccess dbcon = new DBAccess(false, false);
                DataRow drRow = dbcon.GetDataFirstRow(strSQL);
                if (drRow != null)
                {
                    this.dgvLabourCost.Rows[e.RowIndex].Cells[(int)LabourCostCol.CalUnit].Value = CvtFunc.ToString(drRow["STDQtyUnit"]); 
                    this.dgvLabourCost.Rows[e.RowIndex].Cells[(int)LabourCostCol.StandardQty].Value = BaseFunctions.FormatNumeric(drRow["WKSTDQty"], "Ns.2");
                    this.dgvLabourCost.Rows[e.RowIndex].Cells[(int)LabourCostCol.StandardWage].Value = BaseFunctions.FormatNumeric(drRow["WKSalary"], "Ns.2");
                    this.dgvLabourCost.Rows[e.RowIndex].Cells[(int)LabourCostCol.StandardWage26].Value = BaseFunctions.FormatNumeric(drRow["WKSTDSalary"], "Ns.2");
                    this.dgvLabourCost.Rows[e.RowIndex].Cells[(int)LabourCostCol.UnitCost].Value = BaseFunctions.FormatNumeric(drRow["WKUnitCost"], "Ns.6");                    
                }
                dbcon.CloseCon();
            }
            if (e.ColumnIndex == (int)LabourCostCol.WKName)
            {
                if (CvtFunc.ToString(this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKID].Value) == "")
                {
                    this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKID].Value = DataFunctions.GetFieldValue("rmWorkingProcedure", "WorkingProcedureID", "WorkingProcedureName='" + CvtFunc.ToString(this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKName].Value) + "'");
                    string strWKID = CvtFunc.ToString(this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKID].Value);
                    this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKName].Value = DataFunctions.GetFieldValue("rmWorkingProcedure", "WorkingProcedureName", "WorkingProcedureID='" + strWKID + "'");
                    this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKOutName].Value = DataFunctions.GetFieldValue("rmWorkingProcedure", "WKOut", "WorkingProcedureID='" + strWKID + "'");
                }
            }
            else if (e.ColumnIndex == (int)LabourCostCol.CutType)
            {
                string strCutType = CvtFunc.ToString ( this.dgvLabourCost.Rows[e.RowIndex].Cells[(int)LabourCostCol.CutType].Value) ;
                double dblCutType = CvtFunc.ToDouble ( DataFunctions.GetFieldValue ( "rmCutType","CutTimes","CutType='"+ strCutType +"'"));
                if (dblCutType == 0 )
                {
                    dblCutType = CvtFunc.ToDouble(strCutType);
                }
                double dblWorkQty = CvtFunc.ToDouble(this.dgvLabourCost.Rows[e.RowIndex].Cells[(int)LabourCostCol.WorkQty].Value);
                if (dblWorkQty != 0)
                    this.dgvLabourCost.Rows[e.RowIndex].Cells[(int)LabourCostCol.TotalQty].Value = BaseFunctions.FormatNumeric(dblWorkQty / dblCutType, "ns.0");
                else
                    this.dgvLabourCost.Rows[e.RowIndex].Cells[(int)LabourCostCol.TotalQty].Value = "0";
            }
            else if (e.ColumnIndex == (int)LabourCostCol.ItemNo)
            {
                if (DataFunctions.GetFieldValue("iminvmaster", "FItemID", "ItemNo='" + CvtFunc.ToString(this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.ItemNo].Value) + "'") != "")
                {
                    this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.FItemID].Value = DataFunctions.GetFieldValue("imInvMaster", "FItemID", "ItemNo='" + CvtFunc.ToString(this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.ItemNo].Value) + "'");
                }
            }
            if (e.ColumnIndex == (int)LabourCostCol.FItemID)
            {
                string strFItemID = CvtFunc.ToString(this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.FItemID].Value);
                this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.ItemNo].Value = DataFunctions.GetFieldValue("iminvmaster", "itemno", "FItemID='" + strFItemID + "'");
                this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.ItemName].Value = DataFunctions.GetFieldValue("iminvmaster", "itemname", "FItemID='" + strFItemID + "'");                
            }
            dgvLabourCost.EndEdit();
        }

        private void dgvLabourCost_CellEnter(object sender, DataGridViewCellEventArgs e)
        {
            if (this.dgvLabourCost.CurrentCell.ColumnIndex == (int)LabourCostCol.DelButton)
            {
                this.dgvLabourCost.CurrentCell.Selected = false;
            }
            if (CvtFunc.ToDouble(this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.RecID].Value) > 0)
            {
                this.dgvLabourCost.Columns[(int)LabourCostCol.WKName].ReadOnly = false;
            }
            ChangeGridSelectRowBackColor(dgvLabourCost);
        }

        private void dgvLabourCost_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (this.dgvLabourCost.CurrentCell.ColumnIndex == (int)LabourCostCol.DelButton)
            {
                this.dgvLabourCost.CurrentCell.Selected = false;
            }
        }

        private void dgvLabourCost_CellLeave(object sender, DataGridViewCellEventArgs e)
        {
            this.dgvLabourCost.EndEdit();
            if (e.ColumnIndex == (int)LabourCostCol.WorkQty || e.ColumnIndex == (int)LabourCostCol.CutType)
            {
                this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.TotalQty].Value =BaseFunctions.FormatNumeric(  CvtFunc.ToDouble(this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WorkQty].Value) / CvtFunc.ToDouble(this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.CutType].Value),"Ns.2");

            }
            else if (e.ColumnIndex == (int)LabourCostCol.ItemNo)
            {
                if (CvtFunc.ToString(this.dgvLabourCost.Rows[e.RowIndex].Cells[(int)LabourCostCol.ItemNo].Value) == "")
                {
                    this.dgvLabourCost.Rows[e.RowIndex].Cells[(int)LabourCostCol.ItemNo].Value = "";
                    this.dgvLabourCost.Rows[e.RowIndex].Cells[(int)LabourCostCol.ItemName].Value = "";
                    this.dgvLabourCost.Rows[e.RowIndex].Cells[(int)LabourCostCol.FItemID].Value = "0";
                }
            }
            else if (e.ColumnIndex == (int)LabourCostCol.WorkQty)
            {
                this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WorkQty].Value = BaseFunctions.FormatNumeric(this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WorkQty].Value, "Ns.2");
            }
            else if (e.ColumnIndex == (int)LabourCostCol.WKName)
            {
                if (CvtFunc.ToDouble(this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.RecID].Value) <= 0)
                {
                    string strWKPriceType = CvtFunc.ToString(this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKPriceType].Value);
                    double dblWorkCost = DataFunctions.GetCategoryWKWorkCost(txtCategoryID.Text, CvtFunc.ToString(this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKID].Value), strWKPriceType);
                    if (dblWorkCost > 0)
                    {
                        this.dgvLabourCost.Rows[e.RowIndex].Cells[(int)LabourCostCol.WorkCost].Value = BaseFunctions.FormatNumeric(dblWorkCost, "Ns.2");
                    }
                }
            }
            
            if (e.ColumnIndex == (int)LabourCostCol.StandardQty )
            {
                this.dgvLabourCost.Rows[e.RowIndex].Cells[(int)LabourCostCol.StandardQty].Value = BaseFunctions.FormatNumeric(this.dgvLabourCost.Rows[e.RowIndex].Cells[(int)LabourCostCol.StandardQty].Value, "ns.2"); 
            }
            else if (e.ColumnIndex == (int)LabourCostCol.StandardWage)
            {
                this.dgvLabourCost.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = BaseFunctions.FormatNumeric(this.dgvLabourCost.Rows[e.RowIndex].Cells[e.ColumnIndex].Value, "Ns.2");
            }
            else if (e.ColumnIndex == (int)LabourCostCol.StandardWage26)
            {
                this.dgvLabourCost.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = BaseFunctions.FormatNumeric(this.dgvLabourCost.Rows[e.RowIndex].Cells[e.ColumnIndex].Value, "Ns.2");
            }
            else if (e.ColumnIndex == (int)LabourCostCol.TotalQty)
            {
                this.dgvLabourCost.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = BaseFunctions.FormatNumeric(this.dgvLabourCost.Rows[e.RowIndex].Cells[e.ColumnIndex].Value, "Ns.2");
            }
            else if (e.ColumnIndex == (int)LabourCostCol.UsedHours)
            {
                this.dgvLabourCost.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = BaseFunctions.FormatNumeric(this.dgvLabourCost.Rows[e.RowIndex].Cells[e.ColumnIndex].Value, "Ns.2");
            }
            else if (e.ColumnIndex == (int)LabourCostCol.UnitCost)
            {
                this.dgvLabourCost.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = BaseFunctions.FormatNumeric(this.dgvLabourCost.Rows[e.RowIndex].Cells[e.ColumnIndex].Value, "Ns.8");
            }

            if ( CvtFunc.ToString(dgvLabourCost.Rows[e.RowIndex].Cells[(int)LabourCostCol.ValueChanged].Value) == "1" && (e.ColumnIndex == (int)LabourCostCol.CalUnit || e.ColumnIndex == (int)LabourCostCol.CutType || e.ColumnIndex == (int)LabourCostCol.StandardQty
                || e.ColumnIndex == (int)LabourCostCol.UsedHours || e.ColumnIndex == (int)LabourCostCol.UnitCost || e.ColumnIndex == (int)LabourCostCol.WorkCost
                || e.ColumnIndex == (int)LabourCostCol.TotalQty || e.ColumnIndex == (int)LabourCostCol.WorkQty || e.ColumnIndex == (int)LabourCostCol.WKName))
            {
                string strErrMsg = string.Empty;
                if (CheckDtlRow_LabourCost(ref strErrMsg))
                {
                    Update_Detail_LabourCost(this.dgvLabourCost.Rows[e.RowIndex]);
                }
            }
        }

        private void dgvLabourCost_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            return;
        }

        private void dgvLabourCost_RowEnter(object sender, DataGridViewCellEventArgs e)
        {
            base.SetGridViewDelImage(this.dgvLabourCost, e, (int)LabourCostCol.DelButton);
            //if (this.formStatus == FormStatus.Query)
            //{
            //    dgvLabourCost.Enabled = false;
            //    return;
            //}
            string strErrMsg = "";
            if (dgvLabourCost.CurrentRow != null && CvtFunc.ToInt(dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.ValueChanged].Value) > 0)
            {
                if (CheckDtlRow_LabourCost (ref strErrMsg))
                {
                    if (!Update_Detail_LabourCost(this.dgvLabourCost.Rows[this.dgvLabourCost.CurrentCell.RowIndex]))
                    {
                        return;
                    }
                }
                else
                {
                    return;
                }
            }

        }

        private void dgvLabourCost_MouseDown(object sender, MouseEventArgs e)
        {

            mhtiDtl = this.dgvLabourCost.HitTest(e.X, e.Y);

            //System.Windows.Forms.DataGridView.HitTestInfo hti;
            //hti = this.dgvLabourCost.HitTest(e.X, e.Y);
            //switch (hti.Type)
            //{
            //    case System.Windows.Forms.DataGridViewHitTestType.Cell:
            //        break;
            //}
        }

        private bool dgvLabourCost_KeyDownEvent(System.Windows.Forms.Keys keyData)
        {
            string strErrMsg = "";
            int j;
            switch (keyData)
            {
                case Keys.Down:
                    #region Key Down

                    this.dgvLabourCost.EndEdit();
                    if (CvtFunc.ToInt(dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.RecID].Value) > 0)
                    {
                        if (CvtFunc.ToInt(dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.ValueChanged].Value) > 0)
                        {

                            if (CheckDtlRow_LabourCost(ref strErrMsg))
                            {

                                if (!Update_Detail_LabourCost(this.dgvLabourCost.Rows[this.dgvLabourCost.CurrentCell.RowIndex]))
                                {
                                    return true;
                                }
                            }
                            else
                            {
                                MessageBox.Show(strErrMsg, SysVar.WarnTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                                return true;
                            }
                        }
                        if (dgvLabourCost.CurrentCell.RowIndex < dgvLabourCost.Rows.Count - 1)
                        {
                            dgvLabourCost.CurrentCell = this.dgvLabourCost.Rows[dgvLabourCost.CurrentCell.RowIndex + 1].Cells[(int)LabourCostCol.WKName];
                        }
                        else
                        {
                            if (this.formStatus == FormStatus.Update) AddDtlRow(this.dgvLabourCost.Name);
                        }
                    }
                    else
                    {
                        if (CheckDtlRow_LabourCost (ref strErrMsg))
                        {
                            if (!Update_Detail_LabourCost (this.dgvLabourCost.Rows[this.dgvLabourCost.CurrentCell.RowIndex]))
                            {
                                return true;
                            }
                            if (this.formStatus == FormStatus.Update) AddDtlRow(this.dgvLabourCost.Name);
                        }
                        else
                        {
                            MessageBox.Show(strErrMsg, SysVar.WarnTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                            return true;
                        }
                    }
                    return true;


                    #endregion
                case Keys.Up:
                    #region Key Up
                    if (CvtFunc.ToInt(dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.RecID].Value) > 0)
                    {
                        if (CvtFunc.ToInt(dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.ValueChanged].Value) > 0)
                        {
                            if (CheckDtlRow_LabourCost (ref strErrMsg))
                            {
                                if (!Update_Detail_LabourCost  (this.dgvLabourCost.Rows[this.dgvLabourCost.CurrentCell.RowIndex])) return true;
                            }
                            else
                            {
                                MessageBox.Show(strErrMsg, SysVar.WarnTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                                return true;
                            }
                        }
                        if (dgvLabourCost.CurrentCell.RowIndex > 0)
                        {
                            dgvLabourCost.CurrentCell = this.dgvLabourCost.Rows[dgvLabourCost.CurrentCell.RowIndex - 1].Cells[(int)LabourCostCol.WKName];
                        }
                    }
                    else
                    {
                        if (CheckDtlRow_LabourCost (ref strErrMsg))
                        {
                            if (!Update_Detail_LabourCost (this.dgvLabourCost.Rows[this.dgvLabourCost.CurrentCell.RowIndex])) return true;
                            if (dgvLabourCost.CurrentCell.RowIndex > 0)
                            {
                                dgvLabourCost.CurrentCell = this.dgvLabourCost.Rows[dgvLabourCost.CurrentCell.RowIndex - 1].Cells[(int)LabourCostCol.WKName];
                            }
                        }
                        else if (dgvLabourCost.Rows.Count > 1)
                        {

                            this.dgvLabourCost.Rows.Remove(this.dgvLabourCost.CurrentRow);
                            dgvLabourCost.CurrentCell = this.dgvLabourCost.Rows[dgvLabourCost.Rows.Count - 1].Cells[(int)LabourCostCol.WKName];
                        }
                    }
                    return true;
                    #endregion
                case Keys.Enter:
                    #region Key Enter
                    this.dgvLabourCost.EndEdit();
                    j = BaseFunctions.GetGridViewLastEnabledEditColumn(this.dgvLabourCost);
                    if (dgvLabourCost.CurrentCell.ColumnIndex == j)
                    {
                        if (CvtFunc.ToInt(dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.RecID].Value) > 0)
                        {
                            if (CvtFunc.ToInt(dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.ValueChanged].Value) > 0)
                            {
                                if (CheckDtlRow_LabourCost (ref strErrMsg))
                                {
                                    if (!Update_Detail_LabourCost (this.dgvLabourCost.Rows[this.dgvLabourCost.CurrentCell.RowIndex])) return true;
                                }
                                else
                                {
                                    MessageBox.Show(strErrMsg, SysVar.WarnTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                                    return true;
                                }
                            }
                        }
                        else
                        {
                            if (CheckDtlRow_LabourCost (ref strErrMsg))
                            {
                                if (!Update_Detail_LabourCost (this.dgvLabourCost.Rows[this.dgvLabourCost.CurrentCell.RowIndex])) return true;
                            }
                            else
                            {
                                MessageBox.Show(strErrMsg, SysVar.WarnTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                                return true;
                            }

                        }
                        if (dgvLabourCost.CurrentCell.RowIndex < dgvLabourCost.Rows.Count - 1)
                        {
                            dgvLabourCost.CurrentCell = this.dgvLabourCost.Rows[dgvLabourCost.CurrentCell.RowIndex + 1].Cells[(int)LabourCostCol.WKName];
                        }
                        else
                        {
                            if (this.formStatus == FormStatus.Update) AddDtlRow(this.dgvLabourCost.Name);
                        }
                    }
                    else
                    {
                        j = BaseFunctions.GetGridViewNextEnabledEditColumn(dgvLabourCost, dgvLabourCost.CurrentCell.ColumnIndex);
                        if (j >= 0) SendKeys.Send("{Tab}");
                        //  if (j >= 0) dgvLabourCost.CurrentCell = this.dgvLabourCost.Rows[dgvLabourCost.CurrentCell.RowIndex].Cells[j];
                    }

                    return true;
                    #endregion
            }
            return false;
        }



        private void dgvLabourCost_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
        {
            // 对第1列相同单元格进行合并
            if (e.ColumnIndex == (int)LabourCostCol.WKName  && e.RowIndex != -1)
            {
                using
                    (
                    Brush gridBrush = new SolidBrush(this.dgvLabourCost.GridColor),
                    backColorBrush = new SolidBrush(e.CellStyle.BackColor)
                    )
                {
                    using (Pen gridLinePen = new Pen(gridBrush))
                    {
                        // 清除单元格
                        e.Graphics.FillRectangle(backColorBrush, e.CellBounds);

                        // 画 Grid 边线（仅画单元格的底边线和右边线）
                        //   如果下一行和当前行的数据不同，则在当前的单元格画一条底边线
                        if (e.RowIndex < dgvLabourCost.Rows.Count - 1 && dgvLabourCost.Rows[e.RowIndex + 1].Cells[e.ColumnIndex].Value.ToString() != e.Value.ToString())
                            e.Graphics.DrawLine(gridLinePen, e.CellBounds.Left, e.CellBounds.Bottom - 1, e.CellBounds.Right - 1, e.CellBounds.Bottom - 1);
                        // 画右边线
                        e.Graphics.DrawLine(gridLinePen, e.CellBounds.Right - 1, e.CellBounds.Top, e.CellBounds.Right - 1, e.CellBounds.Bottom);

                        // 画（填写）单元格内容，相同的内容的单元格只填写第一个
                        if (e.Value != null)
                        {
                            if (e.RowIndex > 0 && dgvLabourCost.Rows[e.RowIndex - 1].Cells[e.ColumnIndex].Value.ToString() == e.Value.ToString())
                            { }
                            else
                            {
                                e.Graphics.DrawString((String)e.Value, e.CellStyle.Font, Brushes.Black, e.CellBounds.X + 2, e.CellBounds.Y + 5, StringFormat.GenericDefault);
                            }
                        }
                        e.Handled = true;
                    }
                }
            }
        }


        #endregion

        private void btnTallyCalculate_Click(object sender, EventArgs e)
        {
            string strSQL= string.Empty ;
            if (this.tbcMain.SelectedTab == tbpBOM)
            {
                if (!this.Update_Detail(dgvBOM.CurrentRow)) return;
                if (this.dgvBOM.CurrentRow == null) return;
                if (this.dgvBOM.CurrentCell == null) return;
                if (CvtFunc.ToString(this.dgvBOM.CurrentRow.Cells[(int)DtlCol.ItemNo].Value) == "") return;
                string strRecID = CvtFunc.ToString(this.dgvBOM.CurrentRow.Cells[(int)DtlCol.RecID].Value);
                frmRMWKFormula frmCal = new frmRMWKFormula(strRecID, frmRMWKFormula.FormulaType.FromProductBOM);
                frmCal.StartPosition = FormStartPosition.CenterParent;
                string strCaption = "定额数量  计算公式选择： " + CvtFunc.ToString(this.dgvBOM.CurrentRow.Cells[(int)DtlCol.WKName].Value) + "    " + CvtFunc.ToString(this.dgvBOM.CurrentRow.Cells[(int)DtlCol.ItemNo].Value) + "  " + CvtFunc.ToString(this.dgvBOM.CurrentRow.Cells[(int)DtlCol.ItemName].Value);
                frmCal.Text = strCaption;
                frmCal.ShowDialog();
                strSQL = "select * from rmProductBOMDetail where RecID='" + strRecID + "'";
               
            }
            else if (this.tbcMain.SelectedTab == tbpOtherCost)
            {
                if (this.dgvLabourCost.CurrentRow == null) return;
                if (this.dgvLabourCost.CurrentCell == null) return;
                this.dgvLabourCost.EndEdit();
                if (!this.Update_Detail_LabourCost ( dgvLabourCost.CurrentRow )) return ;
                string strRecID = CvtFunc.ToString(this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.RecID].Value);
                frmRMWKFormula frmCal = new frmRMWKFormula(strRecID, frmRMWKFormula.FormulaType.OtherProductBOM);
                frmCal.StartPosition = FormStartPosition.CenterParent;
                frmCal.Text = "项目分摊  计算公式选择： " + CvtFunc.ToString(this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKName].Value) + "    " + txtProductName.Text;
                frmCal.ShowDialog();
                strSQL = "select * from rmProductBOMLabourCost where RecID='" + strRecID + "'";               
            }
            else if (this.tbcMain.SelectedTab == tbpSemiProduct)
            {
                if (this.dgvSemiProduct.CurrentRow == null) return;
                if (this.dgvSemiProduct.CurrentCell == null) return;
                this.dgvSemiProduct.EndEdit();
                if (!this.Update_SemiProductDetail(dgvSemiProduct.CurrentRow)) return;
                string strRecID = CvtFunc.ToString(this.dgvSemiProduct.CurrentRow.Cells["RecID"].Value);
                frmRMWKFormula frmCal = new frmRMWKFormula(strRecID, frmRMWKFormula.FormulaType.SemiProductBOM);
                frmCal.StartPosition = FormStartPosition.CenterParent;
                frmCal.Text = "半成品  数量计算公式选择： " + CvtFunc.ToString(this.dgvSemiProduct.CurrentRow.Cells["SemiCode"].Value) + "    " + txtProductName.Text;
                frmCal.ShowDialog();
                strSQL = "select * from rmProductBOMSemi where RecID='" + strRecID + "'";             
            }

            if (this.tbcMain.SelectedTab  == tbpBOM)
            {
                DataRow drRow = mdbcon.GetDataFirstRow(strSQL);
                RMProductBOMHdrDAL rmDAL = new RMProductBOMHdrDAL();
                rmDAL.UpdateCost(mdbcon, drRow);

                this.dgvBOM.CurrentRow.Cells[(int)DtlCol.Qty].Value = drRow["Qty"];
                this.dgvBOM.CurrentRow.Cells[(int)DtlCol.TotalCost].Value = drRow["TotalCost"];
                this.dgvBOM.EndEdit();
                this.dgvBOM.RefreshEdit();
            }
            else if (this.tbcMain.SelectedTab == tbpOtherCost)
            {
                DataRow drRow = mdbcon.GetDataFirstRow(strSQL);
                RMProductBOMHdrDAL rmDAL = new RMProductBOMHdrDAL();
                rmDAL.UpdateLabourCostDetail(mdbcon, drRow);
                if (drRow != null)
                {
                    this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WorkQty].Value = drRow["WorkQty"];
                    this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.TotalQty].Value = drRow["TotalQty"];
                    this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.TotWorkCost].Value = drRow["DetailTotWorkCost"];
                    this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.UsedHours].Value = drRow["SpendHours"];
                    this.dgvLabourCost.EndEdit();
                    this.dgvLabourCost.RefreshEdit();
                }
            }
            else if (this.tbcMain.SelectedTab == tbpSemiProduct)
            {
                DataRow drRow = mdbcon.GetDataFirstRow(strSQL);
                RMProductBOMHdrDAL rmDAL = new RMProductBOMHdrDAL();
                rmDAL.UpdateSemiProductDetail(mdbcon, drRow,FormStatus.Update);
                if (drRow != null)
                {
                    this.dgvSemiProduct.CurrentRow.Cells["Quantity"].Value = drRow["Quantity"];
                    this.dgvSemiProduct.CurrentRow.Cells["WorkCost"].Value = drRow["WorkCost"];
                    this.dgvSemiProduct.CurrentRow.Cells["LabourCost"].Value = drRow["LabourCost"];
                    this.dgvSemiProduct.CurrentRow.Cells["BOMCost"].Value = drRow["BOMCost"];
                    this.dgvSemiProduct.CurrentRow.Cells["SemiTotalCost"].Value = drRow["SemiTotalCost"];                    
                    this.dgvSemiProduct.EndEdit();
                    this.dgvSemiProduct.RefreshEdit();
                }
            }
            ShowFormula(this.dgvBOM.CurrentRow.Index);
        }

        private void ToAllVersionToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (this.tbcMain.SelectedTab != tbpBOM) return; 
            if (this.dgvBOM.CurrentRow == null) return;
            if (CvtFunc.ToString(this.dgvBOM.CurrentRow.Cells[(int)DtlCol.ItemNo].Value) == "") return;
            if (CvtFunc.ToDouble  (this.dgvBOM.CurrentRow.Cells[(int)DtlCol.RecID].Value ) <=0) return ;
            string strOldFItemID = CvtFunc.ToString(this.dgvBOM.CurrentRow.Cells[(int)DtlCol.FItemID].Value);
            string strOldItemNo = CvtFunc.ToString(this.dgvBOM.CurrentRow.Cells[(int)DtlCol.ItemNo].Value);
            string strOldSupNo = CvtFunc.ToString(this.dgvBOM.CurrentRow.Cells[(int)DtlCol.SupNo].Value); 
            Dtl_LookUp( (int)DtlCol.ItemNo , this.dgvBOM.Name.ToString());
            UpdateDetailByNewItemNo(true, strOldFItemID, strOldSupNo);
        }


        private void UpdateDetailByNewItemNo(bool blnVerClosed, string strOldFItemID, string strOldSupNo)
        {
            if (this.formStatus == FormStatus.Query) return;
            RMProductBOMHdrDAL rmDAL = new RMProductBOMHdrDAL();
            string strItemFItemID = CvtFunc.ToString(this.dgvBOM.CurrentRow.Cells[(int)DtlCol.FItemID].Value);
            string strItemNo = CvtFunc.ToString(this.dgvBOM.CurrentRow.Cells[(int)DtlCol.ItemNo].Value);
            string strSupNo = CvtFunc.ToString(this.dgvBOM.CurrentRow.Cells[(int)DtlCol.SupNo].Value);
            string strSQL = "select * from rmProductBOMDetail where FItemID='" + strOldFItemID + "' and supno='" + strOldSupNo + "' " + (blnVerClosed ? "" : "and ProductFItemID in ( select ProductFItemID from rmProductBOMRev where VerClosed=0)") + " ";
            DataTable dtBOM = mdbcon.GetDataTable(strSQL);
            foreach (DataRow drBOM in dtBOM.Rows)
            {
                drBOM["SupNo"] = this.dgvBOM.CurrentRow.Cells[(int)DtlCol.SupNo].Value;
                drBOM["SupName"] = this.dgvBOM.CurrentRow.Cells[(int)DtlCol.SupName].Value;
                drBOM["FItemID"] = this.dgvBOM.CurrentRow.Cells[(int)DtlCol.FItemID].Value;
                drBOM["ItemNo"] = this.dgvBOM.CurrentRow.Cells[(int)DtlCol.ItemNo].Value;
                drBOM["Price"] = this.dgvBOM.CurrentRow.Cells[(int)DtlCol.Price].Value;
                drBOM["PriceUnit"] = this.dgvBOM.CurrentRow.Cells[(int)DtlCol.PriceUnit].Value;
                rmDAL.UpdateBOMDetail(mdbcon, drBOM);

                rmDAL.ReCalSemiProductCost(mdbcon, txtCategoryID.Text, txtProductFItemID.Text, txtSetID.Text, txtTechnicsName.Text);
            }
        }

        private void ToOpenToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (this.tbcMain.SelectedTab != tbpBOM) return;
            if (this.dgvBOM.CurrentRow == null) return;
            if (CvtFunc.ToString(this.dgvBOM.CurrentRow.Cells[(int)DtlCol.ItemNo].Value) == "") return;
            if (CvtFunc.ToDouble(this.dgvBOM.CurrentRow.Cells[(int)DtlCol.RecID].Value) <= 0) return;
            string strOldItemFItemID = CvtFunc.ToString(this.dgvBOM.CurrentRow.Cells[(int)DtlCol.FItemID].Value);
            string strOldSupNo = CvtFunc.ToString(this.dgvBOM.CurrentRow.Cells[(int)DtlCol.SupNo].Value);
            Dtl_LookUp((int)DtlCol.ItemNo, this.dgvBOM.Name.ToString());
            UpdateDetailByNewItemNo(false, strOldItemFItemID, strOldSupNo);
        }

        private void btnCopyTo_Click(object sender, EventArgs e)
        {
            if (this.formStatus == FormStatus.AddNew) return;
            RMProductBOMHdrDAL rmDAL = new RMProductBOMHdrDAL();
            DBAccess dbcon = new DBAccess(false, false);
            try
            {
                frmRMProductBOMCopy frmCopy = new frmRMProductBOMCopy(txtCategoryID.Text, txtSetID.Text, txtProductFItemID.Text,txtTechnicsName.Text);
                bool blnSuccess = false;
                string strCategoryID = "";
                string strSetID ="";
                string strProductFItemID="";
                string strTechnicsName = "";
                frmCopy.CopyTo(ref blnSuccess, ref strCategoryID, ref strSetID, ref strProductFItemID,ref strTechnicsName);

                if (blnSuccess == false) return;

                dbcon.BeginTran();
                string strRecID = CvtFunc.ToString(this.dgList.CurrentRow.Cells["RecID"].Value);
                DataRow drHdr = dbcon.GetDataFirstRow("select * from rmProductBOMHdr where ProductFItemID='" + txtProductFItemID.Text + "' and TechnicsName='"+ txtTechnicsName.Text +"'");

                if (rmDAL.CopyTo(dbcon, drHdr, strCategoryID,strSetID ,strProductFItemID,strTechnicsName))
                {
                    dbcon.CommitTran();
                    this.dgList.RefreshData();
                    this.dgList.Focus();
                    MessageBox.Show("复制成功完成！", "PDM", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    dbcon.RollbackTran();
                }
            }
            catch (Exception ex)
            {
                dbcon.RollbackTran();
                MsgBoxEx.Show(ex.ToString());
                return;
            }

            dbcon.CloseCon();
        }

        private void btnCopyBOMToLabour_Click(object sender, EventArgs e)
        {
            frmRMCopyBOMToLabourCost frmLabourCost = new frmRMCopyBOMToLabourCost();
            frmRMCopyBOMToLabourCost.Parameter para = new frmRMCopyBOMToLabourCost.Parameter();
            para.strCategoryName = txtCategoryName.Text;
            para.strSetName = txtSetName.Text;
            para.strProductName = txtProductName.Text;
            para.strTechnicsName = txtTechnicsName.Text;
            para.strCategoryID = txtCategoryID.Text;
            para.strSetID = txtSetID.Text;
            para.strProductFitemID = txtProductFItemID.Text;
 
            frmLabourCost.ShowFrom(frmRMCopyBOMToLabourCost.FromType.BOM , this.dgvBOM, para);
            if (frmLabourCost.mblnHasReturn)
            {
                foreach (DataGridViewRow dgvRow in frmLabourCost.dgvBOM.Rows)
                {
                    if (CvtFunc.ToBoolean(dgvRow.Cells["SEL"].Value))
                    {
                        
                        string strWKID = CvtFunc.ToString(dgvRow.Cells["WKID"].Value);
                        string strWKName = CvtFunc.ToString(dgvRow.Cells["WKName"].Value);
                        string strFItemID = CvtFunc.ToString(dgvRow.Cells["FItemID"].Value);
                        string strProductFItemID = CvtFunc.ToString(dgvRow.Cells["ProductFItemID"].Value);
                        string strItemNo = CvtFunc.ToString(dgvRow.Cells["ItemNo"].Value);
                        int intInsertRow = GetLastRowInGridForSpecilaWKName(strWKID);
                        string strErrMsg = "";
                        if (CheckDtlRow_LabourCost(ref strErrMsg))
                        {
                            AddDtlRow(this.dgvLabourCost.Name, intInsertRow);
                        }
                        this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKID].Value = CvtFunc.ToString(dgvRow.Cells["WKID"].Value );
                        this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.WKName].Value = strWKName;
                        this.dgvLabourCost_CellValueChanged(this.dgvLabourCost, new DataGridViewCellEventArgs((int)LabourCostCol.WKName, this.dgvLabourCost.CurrentCell.RowIndex));
                        this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.FItemID].Value = strFItemID;
                        this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.ItemNo].Value = strItemNo;
                     
                        this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.ItemName].Value = DataFunctions.GetFieldValue("iminvmaster", "itemname", "FItemID='" + strFItemID + "'");
                        this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.CategoryID].Value = txtCategoryID.Text;
                        this.dgvLabourCost.CurrentRow.Cells[(int)LabourCostCol.SetID].Value = txtSetID.Text; 
                        this.Update_Detail_LabourCost(this.dgvLabourCost.CurrentRow);
                    }
                }
            }
        }


        private int GetLastRowInGridForSpecilaWKName(string strWKID)
        {
            bool blnFind = false;
            foreach (DataGridViewRow dgvRow in this.dgvLabourCost.Rows)
            {
                if (CvtFunc.ToString(dgvRow.Cells["WKID"].Value) == strWKID)
                {
                    blnFind = true;
                }
                else
                {
                    if (blnFind) return dgvRow.Index;
                }
            }
            return this.dgvLabourCost.Rows.Count - 1;

        }

        private void ShowWorkCost()//计算关键工序的成本
        {

            string strSQL = "select sum(DetailCost),sum(DetailTotWorkCost) from rmProductBOMLabourCost where CategoryID='{0}' and SetID='{1}' and ProductFItemID='{2}' and TechnicsName='{3}' and IsKeyWK=1";
            strSQL = string.Format(strSQL, txtCategoryID.Text , txtSetID.Text ,  txtProductFItemID.Text,txtTechnicsName.Text);
            DataRow  drTotal = mdbcon .GetDataFirstRow(strSQL);
            if (drTotal != null)
            {              
                txtKeyWKWorkCost.Text  =BaseFunctions.FormatNumeric ( CvtFunc.ToDouble(drTotal[1]),"Ns.2");
            }
            txtOtherWorkCost.Text = BaseFunctions.FormatNumeric( CvtFunc.ToDouble(txtTotalWorkCost.Text) - CvtFunc.ToDouble ( txtKeyWKWorkCost.Text) , "Ns.2");
            txtTotalWorkCost2.Text = txtTotalWorkCost.Text;
        }

        private void tvTree_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (e.Node.Nodes.Count == 0) //最后一层
            {
                string strMaterialID = "";
                strMaterialID = CvtFunc.ToString(e.Node.Text.ToString()).Split('-')[0];
                //this.dgList.FindRecord(strMaterialID, "MaterialTypeID");
                string strCond = "where ProductID like '" + strMaterialID + "%'";
                ShowOverViewGrid(strCond);
            }
            else  //最上层
            {
                string strMaterialID = "";
                strMaterialID = CvtFunc.ToString(e.Node.Text.ToString()).Split('-')[0];
                //this.dgList.FindRecord(strMaterialID, "MaterialTypeID");
                string strCond = "where ProductID like '" + strMaterialID + "%'";
                ShowOverViewGrid(strCond);
            }
        }

        private void frmRMProductBOMMtn_FormClosed(object sender, FormClosedEventArgs e)
        {
            mdbcon.CloseCon();
        }




        #region Approval
        private void SetApprovalControlEnable()
        {
            utrapproval1.Enabled = false; txtapprovalPerson1.Enabled = false; datApprovalDate1.Enabled = false;
            utrapproval2.Enabled = false; txtapprovalPerson2.Enabled = false; datApprovalDate2.Enabled = false;
            utrapproval3.Enabled = false; txtapprovalPerson3.Enabled = false; datApprovalDate3.Enabled = false;
            utrapproval4.Enabled = false; txtapprovalPerson4.Enabled = false; datApprovalDate4.Enabled = false;
            utrapproval5.Enabled = false; txtapprovalPerson5.Enabled = false; datApprovalDate5.Enabled = false;

            string strSQL = "select * from mUser where username= '" + SysVar.UserName + "'";
            DataRow drApproval = mdbcon.GetDataFirstRow(strSQL);
            if (drApproval != null)
            {
                if (CvtFunc.ToBoolean(drApproval["approval1"])) utrapproval1.Enabled = true;
                if (CvtFunc.ToBoolean(drApproval["approval2"])) utrapproval2.Enabled = true;
                if (CvtFunc.ToBoolean(drApproval["approval3"])) utrapproval3.Enabled = true;

                if (CvtFunc.ToBoolean(drApproval["approval4"]))
                {
                    if (CvtFunc.ToBoolean(utrapproval1.Text)
                        && CvtFunc.ToBoolean(utrapproval2.Text)
                        && CvtFunc.ToBoolean(utrapproval3.Text))
                    {
                        utrapproval4.Enabled = true;
                        if (!CvtFunc.ToBoolean(utrapproval4.Text))
                        {
                            if (CvtFunc.ToBoolean(drApproval["approval3"])) utrapproval3.Enabled = true;
                            if (CvtFunc.ToBoolean(drApproval["approval2"])) utrapproval2.Enabled = true;
                            if (CvtFunc.ToBoolean(drApproval["approval1"])) utrapproval1.Enabled = true;
                        }
                        else
                        {
                            utrapproval3.Enabled = false;
                            utrapproval2.Enabled = false;
                            utrapproval1.Enabled = false;
                        }
                        
                    }
                }

                if (CvtFunc.ToBoolean(drApproval["approval5"]))
                {
                    if (CvtFunc.ToBoolean(utrapproval1.Text)
                           && CvtFunc.ToBoolean(utrapproval2.Text)
                           && CvtFunc.ToBoolean(utrapproval3.Text)
                           && CvtFunc.ToBoolean(utrapproval4.Text))
                    {
                        utrapproval5.Enabled = true;
                        if (!CvtFunc.ToBoolean(utrapproval5.Text))
                        {
                            if (CvtFunc.ToBoolean(drApproval["approval4"])) utrapproval4.Enabled = true;
                        }
                        else
                        {
                            utrapproval4.Enabled = false;
                        }
                        utrapproval3.Enabled = false;
                        utrapproval2.Enabled = false;
                        utrapproval1.Enabled = false;
                    }
                }
            }
        }

        private void ApprovalCategoryBOM(Control con)
        {
            string strOperType = "";
            string strSQL = "";
            if (con.Name != null)
            {
                if (CvtFunc.ToBoolean(utrapproval1.Text))
                {
                    strSQL = "update rmProductBOMHdr set approval1=1,approvalPerson1='{0}',approvalDate1='{1}' where RecID='{2}'";
                    strSQL = string.Format(strSQL, SysVar.UserName, System.DateTime.Now.ToShortDateString(), this.m_lRecId);
                    mdbcon.ExecuteSql(strSQL);
                    txtapprovalPerson1.Text = SysVar.UserName;
                    datApprovalDate1.Text = BaseFunctions.FormatDate(System.DateTime.Now.Date.ToShortDateString(), DateFormatOption.DateFmtYMD);
                    strOperType = "一级审核";
                }
                else if (CvtFunc.ToBoolean(utrapproval1.Text) == false)
                {
                    strSQL = "update rmProductBOMHdr set approval=0, approvalDate=null , approval1=0,approvalPerson1='',approvalDate1=null where RecID='{2}'";
                    strSQL = string.Format(strSQL, SysVar.UserName, System.DateTime.Now.ToShortDateString(), this.m_lRecId);
                    mdbcon.ExecuteSql(strSQL);
                    txtapprovalPerson1.Text = "";
                    datApprovalDate5.Text = "";
                    strOperType = "一级反审核";
                }
                if (CvtFunc.ToBoolean(utrapproval2.Text))
                {
                    strSQL = "update rmProductBOMHdr set approval2=1,approvalPerson2='{0}',approvalDate2='{1}' where RecID='{2}'";
                    strSQL = string.Format(strSQL, SysVar.UserName, System.DateTime.Now.ToShortDateString(), this.m_lRecId);
                    mdbcon.ExecuteSql(strSQL);
                    txtapprovalPerson2.Text = SysVar.UserName;
                    datApprovalDate2.Text = BaseFunctions.FormatDate(System.DateTime.Now.Date.ToShortDateString(), DateFormatOption.DateFmtYMD);
                    strOperType = "二级审核";
                }
                else if (CvtFunc.ToBoolean(utrapproval2.Text) == false)
                {
                    strSQL = "update rmProductBOMHdr set approval=0, approvalDate=null , approval2=0,approvalPerson2='',approvalDate2=null where RecID='{2}'";
                    strSQL = string.Format(strSQL, SysVar.UserName, System.DateTime.Now.ToShortDateString(), this.m_lRecId);
                    mdbcon.ExecuteSql(strSQL);
                    txtapprovalPerson2.Text = "";
                    datApprovalDate2.Text = "";
                    strOperType = "二级反审核";
                }
                if (CvtFunc.ToBoolean(utrapproval3.Text))
                {
                    strSQL = "update rmProductBOMHdr set approval3=1,approvalPerson3='{0}',approvalDate3='{1}' where RecID='{2}'";
                    strSQL = string.Format(strSQL, SysVar.UserName, System.DateTime.Now.ToShortDateString(), this.m_lRecId);
                    mdbcon.ExecuteSql(strSQL);
                    txtapprovalPerson3.Text = SysVar.UserName;
                    datApprovalDate3.Text = BaseFunctions.FormatDate(System.DateTime.Now.Date.ToShortDateString(), DateFormatOption.DateFmtYMD);
                    strOperType = "三级审核";
                }
                else if (CvtFunc.ToBoolean(utrapproval3.Text) == false)
                {
                    strSQL = "update rmProductBOMHdr set approval=0, approvalDate=null , approval3=0,approvalPerson3='',approvalDate3=null where RecID='{2}'";
                    strSQL = string.Format(strSQL, SysVar.UserName, System.DateTime.Now.ToShortDateString(), this.m_lRecId);
                    mdbcon.ExecuteSql(strSQL);
                    txtapprovalPerson3.Text = "";
                    datApprovalDate3.Text = "";
                    strOperType = "三级审核";
                }
                if (CvtFunc.ToBoolean(utrapproval4.Text))
                {
                    strSQL = "update rmProductBOMHdr set approval4=1,approvalPerson4='{0}',approvalDate4='{1}' where RecID='{2}'";
                    strSQL = string.Format(strSQL, SysVar.UserName, System.DateTime.Now.ToShortDateString(), this.m_lRecId);
                    mdbcon.ExecuteSql(strSQL);
                    txtapprovalPerson4.Text = SysVar.UserName;
                    datApprovalDate4.Text = BaseFunctions.FormatDate(System.DateTime.Now.Date.ToShortDateString(), DateFormatOption.DateFmtYMD);
                    strOperType = "四级审核";
                }
                else if (CvtFunc.ToBoolean(utrapproval4.Text) == false)
                {
                    strSQL = "update rmProductBOMHdr set approval=0, approvalDate=null , approval4=0,approvalPerson4='',approvalDate4=null where RecID='{2}'";
                    strSQL = string.Format(strSQL, SysVar.UserName, System.DateTime.Now.ToShortDateString(), this.m_lRecId);
                    mdbcon.ExecuteSql(strSQL);
                    txtapprovalPerson4.Text = "";
                    datApprovalDate4.Text = "";
                    strOperType = "四级反审核";
                }
                if (CvtFunc.ToBoolean(utrapproval5.Text))
                {
                    strSQL = "update rmProductBOMHdr set approval=1, approvalDate='{1}' , approval5=1,approvalPerson5='{0}',approvalDate5='{1}' where RecID='{2}'";
                    strSQL = string.Format(strSQL, SysVar.UserName, System.DateTime.Now.ToShortDateString(), this.m_lRecId);
                    mdbcon.ExecuteSql(strSQL);
                    utrapproval.Text = "Yes";
                    txtapprovalPerson5.Text = SysVar.UserName;
                    datApprovalDate5.Text = BaseFunctions.FormatDate(System.DateTime.Now.Date.ToShortDateString(), DateFormatOption.DateFmtYMD);
                    //this.formStatus = FormStatus.Query;
                    //frmParameter.FillContent(this.m_lRecId.ToString());
                    strOperType = "五级审核";
                }
                else if (CvtFunc.ToBoolean(utrapproval5.Text) == false)
                {
                    strSQL = "update rmProductBOMHdr set approval=0, approvalDate=null , approval5=0,approvalPerson5='',approvalDate5=null where RecID='{2}'";
                    strSQL = string.Format(strSQL, SysVar.UserName, System.DateTime.Now.ToShortDateString(), this.m_lRecId);
                    mdbcon.ExecuteSql(strSQL);
                    utrapproval.Text = "No";
                    txtapprovalPerson5.Text = "";
                    datApprovalDate5.Text = "";
                    strOperType = "五级反审核";
                }
                frmParameter.FillContent(this.m_lRecId.ToString());
                AddApproHisory(this.RecID.ToString(), strOperType, mdbcon);

                strSQL = "select RecStamp from " + this.TableName + " where RecID='" + this.RecID + "'";
                DataRow drRow = mdbcon.GetDataFirstRow(strSQL);
                if (drRow != null)
                {
                    this.TimeStamp = (byte[])drRow["RecStamp"];
                }               
            }
        }
        
        private void SetControlByApproLevel()
        {
            toolStrip1.Enabled = true;
            if (CvtFunc.ToBoolean(utrapproval.Text) || CvtFunc.ToBoolean(utrapproval4.Text) || CvtFunc.ToBoolean(utrapproval5.Text))
            {
                //this.formStatus = FormStatus.Query;
                //grpApproval.Enabled = true;
                datApprovalDate.Enabled = true;
                txtapprovalPerson.Enabled = false;
                datApprovalDate.Enabled = false;
                txtRemark.Enabled = false;
                              
                SetApprovalControlEnable();
            }
            //else
            {
                if (CvtFunc.ToBoolean(utrapproval1.Text))
                {
                    dgvBOM.ReadOnly = true;
                    dgvBOM.Columns[(int)DtlCol.DelButton].Visible = false;
                    btnAddLine.Enabled = false;
                    if (this.tbcMain.SelectedTab == tbpBOM)
                    {
                        this.btnTallyCalculate.Enabled = false;
                    }
                    else if (this.formStatus == FormStatus.Update && this.tbcMain.SelectedTab == tbpOtherCost)
                    {
                        this.btnTallyCalculate.Enabled = true;
                    }

                }
                if (CvtFunc.ToBoolean(utrapproval2.Text))
                {
                    dgvLabourCost.ReadOnly = true;
                    dgvLabourCost.Columns[(int)LabourCostCol.DelButton].Visible = false;
                    btnAddLine.Enabled = false;
                }
                if (CvtFunc.ToBoolean(utrapproval3.Text))
                {
                    dgvSemiProduct.Columns["DelLine"].Visible = false;
                    dgvSubSemiProduct.Columns["DelLine"].Visible = false;
                    if ( dgvSemiBOM.Columns.Count >0) dgvSemiBOM.Columns["DelLine"].Visible = false;
                    foreach (DataGridViewColumn dgvCol in this.dgvSemiBOM.Columns)
                    {
                        dgvCol.ReadOnly = true;
                    }
                    foreach (DataGridViewColumn dgvCol in this.dgvSemiProduct.Columns)
                    {
                        dgvCol.ReadOnly = true;
                    }
                    foreach (DataGridViewColumn dgvCol in this.dgvSubSemiProduct.Columns)
                    {
                        dgvCol.ReadOnly = true;
                    }
                    toolStrip1.Enabled = false;
                    this.btnTallyCalculate.Enabled = false;
                }
                if (CvtFunc.ToBoolean(utrapproval4.Text))
                {

                }
                if (CvtFunc.ToBoolean(utrapproval5.Text))
                {

                }
                txtapprovalPerson.Enabled = true;
                datApprovalDate.Enabled = true;
                txtRemark.Enabled = true;
              

            }
        }

        public bool AddApproHisory(string strKeyID, string strOperType, DBAccess dbcon)
        {
            string strSQL = "Insert  Into mApproHisory(UserName,OperDate,OperType,KeyID,TableType)";
            strSQL += "VALUES ( '" + SysVar.UserName + "', getdate(), '" + strOperType + "', '" + strKeyID + "', '" + frmApprovalHistory.TableType.ProductBOM + "' )";
            dbcon.ExecuteSql(strSQL);
            return true;
        }

        #endregion


        #region SemiProduct 半成品
        /// <summary>
        /// 
        /// </summary>
        private void InitSemiTreeHdr()
        {
            string strSQL = @"Select count(*) FROM rmProductBOMSemi where CategoryID='{0}' And SetID='{1}' 
                              And ProductFItemID='{2}' And TechnicsName='{3}' and semicode!='-1' ";
            strSQL = string.Format(strSQL, txtCategoryID.Text, txtSetID.Text, txtProductFItemID.Text , txtTechnicsName.Text);
            if (CvtFunc.ToDouble(mdbcon.GetValue(strSQL)) > 0) return;
            
            string strAddRecID = "";
            DataTable dtInitSemi = new DataTable ();
            dtInitSemi.Columns.Add("SemiRecID", typeof(System.Int32));
            dtInitSemi.Columns.Add("OldRecID", typeof(System.Int32));
            dtInitSemi.Columns.Add("OldParentRecID", typeof(System.Int32)); 
            strSQL = "select * from imCategorySemiProduct where CategoryID='" + txtCategoryID.Text + "'  order by SemiCode";
            DataTable dtSemiHdr = mdbcon.GetDataTable(strSQL);
            foreach (DataRow drSemi in dtSemiHdr.Rows)
            {
                DataRow drInitSemi = dtInitSemi.NewRow(); 
                strSQL = @"INSERT INTO rmProductBOMSemi (SemiCode,SemiName,ParentSemiCode,ParentSemiID,WastageRate,Unit,CategoryID,SetID,ProductFItemID) 
                           VALUES('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}');SELECT @@identity";
                strSQL = string.Format(strSQL,drSemi["SemiCode"] 
                                             ,drSemi["SemiName"]
                                             ,drSemi["ParentSemiCode"]
                                             ,drSemi["ParentSemiID"]
                                             ,drSemi["WastageRate"]
                                             ,drSemi["Unit"]
                                             ,drSemi["CategoryID"]
                                             ,txtSetID.Text 
                                             ,txtProductFItemID.Text 
                                      );
                string strRecID = CvtFunc.ToString(mdbcon.GetValue(strSQL));
                drInitSemi["SemiRecID"] = strRecID;
                drInitSemi["OldRecID"] = drSemi["RecID"];
                drInitSemi["OldParentRecID"] = drSemi["ParentSemiID"];
                dtInitSemi.Rows.Add(drInitSemi);
                strAddRecID += strRecID + ","; 
            }
            if (strAddRecID != "")
            {
                dtInitSemi.AcceptChanges();
                strAddRecID = strAddRecID.Substring(0, strAddRecID.Length - 1);
                strAddRecID ="'" + strAddRecID.Replace(",", "','") +"'" ;
                foreach (DataRow drRow in dtInitSemi.Rows)
                {
                    strSQL = @"UPDATE rmProductBOMSemi set ParentSemiID='{0}' Where ParentSemiID='{1}' and CategoryID='{2}'
                               And SetID ='{3}' and ProductFItemID='{4}'
                               And RecID in ({5})";
                    strSQL = string.Format(strSQL, drRow["SemiRecID"], drRow["OldRecID"]
                                                 ,txtCategoryID.Text ,txtSetID.Text  , txtProductFItemID.Text 
                                                 , strAddRecID);
                    mdbcon.ExecuteSql(strSQL);
                }
            }

            string strParentSemiRecID = mdbcon.GetValue(string.Format(@"select recid from rmProductBOMSemi where CategoryID='{1}' And SetID ='{2}' and ProductFItemID='{3}' and SemiCode='-1'"
                                                                 , "" , txtCategoryID.Text, txtSetID.Text, txtProductFItemID.Text));

            strSQL = @"Update rmProductBOMSemi Set ParentSemiID='{0}'  Where ParentSemiID='{1}' and CategoryID='{2}'
                               And SetID ='{3}' and ProductFItemID='{4}' and SemiCode!='-1' ";
            strSQL = string.Format(strSQL, strParentSemiRecID, 0
                                                 , txtCategoryID.Text, txtSetID.Text, txtProductFItemID.Text
                                                 , strAddRecID);
            mdbcon.ExecuteSql(strSQL);
            RMProductBOMHdrDAL rmDAL = new RMProductBOMHdrDAL();
            rmDAL.ReCalSemiProductCost( mdbcon , txtCategoryID.Text , txtProductFItemID.Text , txtSetID.Text , txtTechnicsName.Text);
        }

        private void AddSemiProduct()
        {


        }

        private void FillSemi()
        {
          
            tvSemi.Nodes.Clear();
            string strSQL = @"Select * FROM rmProductBOMSemi where CategoryID='{0}' And SetID='{1}' 
                              And ProductFItemID='{2}' And TechnicsName='{3}' and  ParentSemiID =0 ";
            strSQL = string.Format(strSQL, txtCategoryID.Text, txtSetID.Text, txtProductFItemID.Text, txtTechnicsName.Text);
            DataRow  drSemiHdr = mdbcon.GetDataFirstRow(strSQL);
            if (drSemiHdr == null)
            {
                string strSQLInsert = @" insert into rmProductBOMSemi(SemiCode,SemiName,CategoryID,SetID,ProductFItemID,TechnicsName)
                            values ( '{0}','{1}','{2}','{3}','{4}','{5}');
                          ";
                strSQLInsert = string.Format(strSQLInsert, "-1", txtProductName.Text, txtCategoryID.Text, txtSetID.Text, txtProductFItemID.Text, txtTechnicsName.Text);
                mdbcon.ExecuteSql(strSQLInsert);

                drSemiHdr = mdbcon.GetDataFirstRow(strSQL);

                InitSemiTreeHdr();
            }
            else
            {

            }
            
            //TreeNode tvNodeHdr = new TreeNode(CvtFunc.ToString(drSemiHdr["SemiName"]));
            //tvNodeHdr.Tag = CvtFunc.ToString(drSemiHdr["RecID"]);
            //tvSemi.Nodes.Add(tvNodeHdr);

            FillSemiHdr(); 
        }

        private void FillSemiHdr()
        {
            string strSQL = @"Select A.RecID,A.SemiCode,isnull(B.SemiName,a.SemiName) as SemiName FROM rmProductBOMSemi A Left Join imSemiProduct B on A.SemiCode=B.SemiCode
                              where A.CategoryID='{0}' And A.SetID='{1}' 
                              And A.ProductFItemID='{2}' And A.TechnicsName='{3}' and  A.ParentSemiID =0 and A.semicode='-1'";
            strSQL = string.Format(strSQL, txtCategoryID.Text, txtSetID.Text,txtProductFItemID.Text , txtTechnicsName.Text);
            DataTable dtSemiHdr = mdbcon.GetDataTable(strSQL);
            foreach (DataRow drSemiHdr in dtSemiHdr.Rows)
            {
                //TreeNode tvNodeHdr = new TreeNode(CvtFunc.ToString(drSemiHdr["SemiCode"]) + "-" + CvtFunc.ToString(drSemiHdr["SemiName"]));
                TreeNode tvNodeHdr = new TreeNode(CvtFunc.ToString(drSemiHdr["SemiName"]));
                tvNodeHdr.Tag = CvtFunc.ToString(drSemiHdr["RecID"]);
                tvSemi.Nodes.Add(tvNodeHdr);  
                //tvNode.Nodes.Add(tvNodeHdr);
                string strRecID = CvtFunc.ToString(tvNodeHdr.Tag);
                strSQL = @"with cte as
                            (
                                select RECID, SemiCode,SemiName,ParentSemiID,0 as lvl from rmProductBOMSemi
                                where recId = {0}
                                union all
                                select D.RECID,d.SemiCode,d.SemiName,D.ParentSemiID,lvl+1 from cte c inner join rmProductBOMSemi d
                                on c.recId = d.ParentSemiID
                            )
                            select * from cte where lvl>0";
                strSQL = string.Format(strSQL, strRecID);
                DataView dvSemi = mdbcon.GetDataTable(strSQL).DefaultView;
                FillSemiProduct(tvNodeHdr, dvSemi);
            }
        }

        private void FillSemiProduct(TreeNode tvNode, DataView dvSemi)
        {
            dvSemi.RowFilter = " ParentSemiID ='" + CvtFunc.ToString(tvNode.Tag) + "'";
            if (dvSemi.Count > 0)
            {
                foreach (DataRowView dgv in dvSemi)
                {
                    string strSemiName =CvtFunc.ToString ( mdbcon.GetValue("select seminame from imSemiProduct where semicode='" + CvtFunc.ToString(dgv["SemiCode"]) + "'"));
                    TreeNode tvNodeHdr = new TreeNode(CvtFunc.ToString(dgv["SemiCode"]) + "-" + strSemiName );
                    tvNodeHdr.Tag = CvtFunc.ToString(dgv["RecID"]);
                    tvNode.Nodes.Add(tvNodeHdr);
                    FillSemiProduct(tvNodeHdr, dvSemi);
                }
            }
        }



        /// <summary>
        /// 初始化 dgvSemiProduct 半成品信息Grid 和 下级半成品信息Grid
        /// </summary>
        /// <param name="dgvGrid"></param>
        private void InitGridSemiProductDtl( DataGridView dgvGrid)
        {
            dgvGrid.Columns.Clear();
            dgvGrid.Rows.Clear();

            DataGridViewTextBoxColumn colSeqNo = new DataGridViewTextBoxColumn();
            colSeqNo.HeaderText = "序号";
            colSeqNo.Visible = false;
            colSeqNo.Name = "SeqNo";
            colSeqNo.Width = 50;
            colSeqNo.ReadOnly = false;
            colSeqNo.SortMode = DataGridViewColumnSortMode.NotSortable;

            DataGridViewTextBoxColumn colProductFItemID = new DataGridViewTextBoxColumn();
            colProductFItemID.HeaderText = "成品编码";
            colProductFItemID.Visible = false;
            colProductFItemID.Name = "ProductFItemID";
            colProductFItemID.Width = 50;
            colProductFItemID.ReadOnly = false;
            colProductFItemID.SortMode = DataGridViewColumnSortMode.NotSortable;

            TextLookUpColumn colTechnicsName = new TextLookUpColumn();
            colTechnicsName.HeaderText = "工艺名称";
            colTechnicsName.Width = 150;
            colTechnicsName.Name = "TechnicsName";
            colTechnicsName.ReadOnly = false;
            colTechnicsName.Visible = false;
            colTechnicsName.SortMode = DataGridViewColumnSortMode.NotSortable;

            DataGridViewListColumn colCategoryID = new DataGridViewListColumn();
            colCategoryID.HeaderText = "类别编码";
            colCategoryID.Width = 80;
            colCategoryID.Name = "CategoryID";
            colCategoryID.ReadOnly = false;
            colCategoryID.Visible = false;
            colCategoryID.SortMode = DataGridViewColumnSortMode.NotSortable;

            DataGridViewListColumn colSetID = new DataGridViewListColumn();
            colSetID.HeaderText = "系列编码";
            colSetID.Width = 80;
            colSetID.Name = "SetID";
            colSetID.ReadOnly = false;
            colSetID.Visible = false;
            colSetID.SortMode = DataGridViewColumnSortMode.NotSortable;

            TextLookUpColumn colParentSemiCode = new TextLookUpColumn();
            colParentSemiCode.HeaderText = "上级半成品编码";
            colParentSemiCode.Width = 150;
            colParentSemiCode.Name = "ParentSemiCode";
            colParentSemiCode.ReadOnly = true;
            colParentSemiCode.Visible = false ;
            colParentSemiCode.SortMode = DataGridViewColumnSortMode.NotSortable;

            TextLookUpColumn colParentSemiID = new TextLookUpColumn();
            colParentSemiID.HeaderText = "半成品编码";
            colParentSemiID.Width = 150;
            colParentSemiID.Name = "ParentSemiID";
            colParentSemiID.ReadOnly = false;
            colParentSemiID.Visible = false ;
            colParentSemiID.SortMode = DataGridViewColumnSortMode.NotSortable;

            TextLookUpColumn colParentRecID = new TextLookUpColumn();
            colParentRecID.HeaderText = "半成品编码";
            colParentRecID.Width = 150;
            colParentRecID.Name = "ParentRecID";
            colParentRecID.ReadOnly = false;
            colParentRecID.Visible = false ;
            colParentRecID.SortMode = DataGridViewColumnSortMode.NotSortable;

            TextLookUpColumn colSemiCode = new TextLookUpColumn();
            colSemiCode.HeaderText = "半成品编码";
            colSemiCode.Width = 150;
            colSemiCode.Name = "SemiCode";
            colSemiCode.ReadOnly = false;
            colSemiCode.Visible = true;
            colSemiCode.SortMode = DataGridViewColumnSortMode.NotSortable;

            DataGridViewTextBoxColumn colSemiName = new DataGridViewTextBoxColumn();
            colSemiName.HeaderText = "半成品名称";
            colSemiName.Visible = true;
            colSemiName.Width = 120;
            colSemiName.Name = "SemiName";
            colSemiName.SortMode = DataGridViewColumnSortMode.NotSortable;

            DataGridViewTextBoxColumn colQuantity = new DataGridViewTextBoxColumn();
            colQuantity.HeaderText = "数量";
            colQuantity.Visible = true;
            colQuantity.Width = 80;
            colQuantity.Name = "Quantity";
            colQuantity.SortMode = DataGridViewColumnSortMode.NotSortable;
            colQuantity.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;
            colQuantity.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;

            DataGridViewTextBoxColumn colUnit = new DataGridViewTextBoxColumn();
            colUnit.HeaderText = "单位";
            colUnit.Visible = true;
            colUnit.Width = 60;
            colUnit.Name = "Unit";
            colUnit.SortMode = DataGridViewColumnSortMode.NotSortable;

            DataGridViewTextBoxColumn colQty = new DataGridViewTextBoxColumn();
            colQty.HeaderText = "定额数量";
            colQty.Width = 70;
            colQty.Visible = false ;
            colQty.Name = "Qty";
            colQty.SortMode = DataGridViewColumnSortMode.NotSortable;
            colQty.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            colQty.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;

            DataGridViewTextBoxColumn colWastageRate = new DataGridViewTextBoxColumn();
            colWastageRate.HeaderText = "损耗率%";
            colWastageRate.Visible = true;
            colWastageRate.Width = 50;
            colWastageRate.Name = "WastageRate";
            colWastageRate.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;
            colWastageRate.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;

            // QtyWastage,DetailCost,LabourCost, TotalCost,
            DataGridViewTextBoxColumn colQtyWastage = new DataGridViewTextBoxColumn();
            colQtyWastage.HeaderText = "损耗数量";
            colQtyWastage.Visible = false;
            colQtyWastage.Width = 70;
            colQtyWastage.Name = "QtyWastage";
            colQtyWastage.SortMode = DataGridViewColumnSortMode.NotSortable;
            colQtyWastage.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            colQtyWastage.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;

            DataGridViewTextBoxColumn colBOMCost = new DataGridViewTextBoxColumn();
            colBOMCost.HeaderText = "材料成本";
            colBOMCost.Visible = true;
            colBOMCost.Width = 70;
            colBOMCost.Name = "BOMCost";
            colBOMCost.SortMode = DataGridViewColumnSortMode.NotSortable;
            colBOMCost.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            colBOMCost.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;

            DataGridViewTextBoxColumn colLabourCost = new DataGridViewTextBoxColumn();
            colLabourCost.HeaderText = "人工成本";
            colLabourCost.Visible = true;
            colLabourCost.Width = 70;
            colLabourCost.Name = "LabourCost";
            colLabourCost.SortMode = DataGridViewColumnSortMode.NotSortable;
            colLabourCost.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;
            colLabourCost.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;

            DataGridViewTextBoxColumn colWorkCost = new DataGridViewTextBoxColumn();
            colWorkCost.HeaderText = "工时费用";
            colWorkCost.Visible = true;
            colWorkCost.Width = 70;
            colWorkCost.Name = "WorkCost";
            colWorkCost.SortMode = DataGridViewColumnSortMode.NotSortable;
            colWorkCost.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;
            colWorkCost.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            
            DataGridViewTextBoxColumn colSemiTotalCost = new DataGridViewTextBoxColumn();
            colSemiTotalCost.HeaderText = "总单价";
            colSemiTotalCost.Visible = true;
            colSemiTotalCost.Width = 80;
            colSemiTotalCost.Name = "SemiTotalCost";
            colSemiTotalCost.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            colSemiTotalCost.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;
            colSemiTotalCost.SortMode = DataGridViewColumnSortMode.NotSortable;

            DataGridViewTextBoxColumn colRecID = new DataGridViewTextBoxColumn();
            colRecID.HeaderText = "RecID";
            colRecID.Visible = false;
            colRecID.Name = "RecID";

            DataGridViewTextBoxColumn colValueChanged = new DataGridViewTextBoxColumn();
            colValueChanged.HeaderText = "ValueChanged";
            colValueChanged.Visible = false;
            colValueChanged.Name = "ValueChanged";

            DataGridViewImageColumn colDel = new DataGridViewImageColumn();
            Bitmap delbitmap = new Bitmap(this.iglSource.Images["Del.ico"]);
            colDel.Width = 20;
            colDel.Name = "DelLine";
            colDel.HeaderText = "";
            colDel.Resizable = DataGridViewTriState.False;

            dgvGrid.Columns.AddRange(new DataGridViewColumn[] { colSeqNo, colProductFItemID ,colTechnicsName,
                                                                    colCategoryID , colSetID  ,colParentRecID,colParentSemiCode, colParentSemiID ,
                                                                    colSemiCode ,colSemiName, colQuantity,  colUnit, colQty, colWastageRate,
                                                                    colQtyWastage,colBOMCost,colLabourCost,colWorkCost, colSemiTotalCost,
                                                                    colRecID, colValueChanged, colDel });

            mDtlColumnReadOnlyArray = new bool[dgvGrid.Columns.Count];
            string[] ColumnWidthArray = DataFunctions.GetGridColumnWidthString(this.Name, this.CurrentMenuInfo.iParameter, SysVar.UserName, this.Name + "." + dgvGrid.Name).Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            for (int i = 0; i < dgvGrid.Columns.Count; i++)
            {
                mDtlColumnReadOnlyArray[i] = dgvGrid.Columns[i].ReadOnly;
                if (ColumnWidthArray.Length == dgvGrid.Columns.Count) dgvGrid.Columns[i].Width = CvtFunc.ToInt(ColumnWidthArray[i]);
            }

            dgvGrid.EditMode = DataGridViewEditMode.EditOnEnter;
            dgvGrid.RowTemplate.Height = 20;
            dgvGrid.RowHeadersWidth = 23;
            dgvGrid.RowHeadersBorderStyle = DataGridViewHeaderBorderStyle.None;
            dgvGrid.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.DisableResizing;
            dgvGrid.ColumnHeadersHeight = 30;
            dgvGrid.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
            dgvGrid.SelectionMode = DataGridViewSelectionMode.CellSelect;
            dgvGrid.AllowUserToResizeRows = false;

            if (dgvGrid.Name == dgvSubSemiProduct.Name)
            {
                foreach (DataGridViewColumn dcCol in this.dgvSubSemiProduct.Columns)
                {
                    dcCol.ReadOnly = true;
                }

                this.dgvSubSemiProduct.Columns["WastageRate"].ReadOnly = false;
            }
        }

        private void FillSemiProductGrid(string strSemiRecID,string strSemiCode, string strSemiName)
        {
            m_bCanTrigerCellValueChangedEven_SemiProduct = false;
            this.dgvSemiProduct.Rows.Clear();
            string strSQL = "";//@"Select * FROM rmProductBOMSemi where semicode='{0}' and seminame='{1}'And CategoryID='{2}' And SetID='{3}' And ProductFItemID='{4}' And TechnicsName='{5}'  ";
            //strSQL = string.Format(strSQL, strSemiCode, strSemiName, txtCategoryID.Text, txtSetID.Text, txtProductFItemID.Text , txtTechnicsName.Text);
            strSQL ="Select * FROM rmProductBOMSemi where RecID='"+ strSemiRecID +"'";
            DataRow drSemi = mdbcon.GetDataFirstRow(strSQL);
            if (drSemi != null)
            {
                this.dgvSemiProduct.Rows.Add();
                this.dgvSemiProduct.Rows[0].Cells["RecID"].Value = drSemi["RecID"];
                this.dgvSemiProduct.Rows[0].Cells["ParentRecID"].Value = drSemi["ParentRecID"];
                this.dgvSemiProduct.Rows[0].Cells["semicode"].Value = drSemi["semicode"];
                this.dgvSemiProduct.Rows[0].Cells["seminame"].Value = CvtFunc.ToString ( mdbcon.GetValue("select seminame from imSemiProduct where semicode='" + drSemi["semicode"] + "'"));
                this.dgvSemiProduct.Rows[0].Cells["ParentSemiID"].Value = drSemi["ParentSemiID"];
                this.dgvSemiProduct.Rows[0].Cells["ParentSemiCode"].Value = drSemi["ParentSemiCode"];
                this.dgvSemiProduct.Rows[0].Cells["CategoryID"].Value = drSemi["CategoryID"];
                this.dgvSemiProduct.Rows[0].Cells["SetID"].Value = drSemi["SetID"];
                this.dgvSemiProduct.Rows[0].Cells["ProductFItemID"].Value = drSemi["ProductFItemID"];
                this.dgvSemiProduct.Rows[0].Cells["TechnicsName"].Value = drSemi["TechnicsName"];
                this.dgvSemiProduct.Rows[0].Cells["Quantity"].Value = drSemi["Quantity"];
                this.dgvSemiProduct.Rows[0].Cells["Unit"].Value = drSemi["Unit"];
                this.dgvSemiProduct.Rows[0].Cells["WastageRate"].Value = drSemi["WastageRate"];
                this.dgvSemiProduct.Rows[0].Cells["WorkCost"].Value = drSemi["WorkCost"];
                this.dgvSemiProduct.Rows[0].Cells["LabourCost"].Value = drSemi["LabourCost"];
                this.dgvSemiProduct.Rows[0].Cells["BOMCost"].Value = drSemi["BOMCost"];
                this.dgvSemiProduct.Rows[0].Cells["SemiTotalCost"].Value = drSemi["SemiTotalCost"];
            }
            this.dgvSemiProduct.EndEdit();
            //base.SetBlankImage(this.dgvSemiProduct);
            if (this.dgvSemiProduct.Rows.Count > 0)
            {
                FillSemiProductGrid_Sub(CvtFunc.ToString(this.dgvSemiProduct.Rows[0].Cells["RecID"].Value));
            }
            else
            {
                this.dgvSubSemiProduct.Rows.Clear();
            }
            m_bCanTrigerCellValueChangedEven_SemiProduct = true;
        }
        // 填充当前选择的半成品的子级半成品
        private void FillSemiProductGrid_Sub(string strRecID)
        {
            this.dgvSubSemiProduct.Rows.Clear();
            if (this.dgvSemiProduct.Rows.Count <= 0) return;
            int intRowsCount = 0;
           
            if (strRecID == "") return;
            string strSQL = @"with cte as
                            (
                                select RECID, SemiCode,SemiName,ParentSemiID,0 as lvl from rmProductBOMSemi
                                where recId = {0}
                                union all
                                select D.RECID,d.SemiCode,d.SemiName,D.ParentSemiID,lvl+1 from cte c inner join rmProductBOMSemi d
                                on c.recId = d.ParentSemiID
                            )
                            select * from cte where lvl=1 order by SemiCode";
            strSQL = string.Format(strSQL, strRecID);
            DataTable dtSemiSub = mdbcon.GetDataTable(strSQL);
            foreach (DataRow drSemiSub in dtSemiSub.Rows)
            {
                strSQL = @"Select * FROM rmProductBOMSemi where recid='{0}'  ";
                strSQL = string.Format(strSQL, drSemiSub["RecID"]);
                DataRow drSemi = mdbcon.GetDataFirstRow(strSQL);
                if (drSemi != null)
                {
                    this.dgvSubSemiProduct.Rows.Add();
                    this.dgvSubSemiProduct.Rows[intRowsCount].Cells["RecID"].Value = drSemi["RecID"];
                    this.dgvSubSemiProduct.Rows[intRowsCount].Cells["ParentRecID"].Value = drSemi["ParentRecID"];
                    this.dgvSubSemiProduct.Rows[intRowsCount].Cells["semicode"].Value = drSemi["semicode"];
                    this.dgvSubSemiProduct.Rows[intRowsCount].Cells["seminame"].Value = CvtFunc.ToString(mdbcon.GetValue("select seminame from imSemiProduct where semicode='" + drSemi["semicode"] + "'"));
                    this.dgvSubSemiProduct.Rows[intRowsCount].Cells["ParentSemiID"].Value = drSemi["ParentSemiID"];
                    this.dgvSubSemiProduct.Rows[intRowsCount].Cells["ParentSemiCode"].Value = drSemi["ParentSemiCode"];
                    this.dgvSubSemiProduct.Rows[intRowsCount].Cells["CategoryID"].Value = drSemi["CategoryID"];
                    this.dgvSubSemiProduct.Rows[intRowsCount].Cells["SetID"].Value = drSemi["SetID"];
                    this.dgvSubSemiProduct.Rows[intRowsCount].Cells["ProductFItemID"].Value = drSemi["ProductFItemID"];
                    this.dgvSubSemiProduct.Rows[intRowsCount].Cells["TechnicsName"].Value = drSemi["TechnicsName"];
                    this.dgvSubSemiProduct.Rows[intRowsCount].Cells["Quantity"].Value = drSemi["Quantity"];
                    this.dgvSubSemiProduct.Rows[intRowsCount].Cells["Unit"].Value = drSemi["Unit"];
                    this.dgvSubSemiProduct.Rows[intRowsCount].Cells["WastageRate"].Value = drSemi["WastageRate"];
                    this.dgvSubSemiProduct.Rows[intRowsCount].Cells["WorkCost"].Value = drSemi["WorkCost"];
                    this.dgvSubSemiProduct.Rows[intRowsCount].Cells["LabourCost"].Value = drSemi["LabourCost"];
                    this.dgvSubSemiProduct.Rows[intRowsCount].Cells["BOMCost"].Value = drSemi["BOMCost"];
                    this.dgvSubSemiProduct.Rows[intRowsCount].Cells["SemiTotalCost"].Value = drSemi["SemiTotalCost"];
                    intRowsCount++;
                }
            }
            if (dtSemiSub.Rows.Count == 0)
            {
                this.dgvSubSemiProduct.Rows.Clear();
                FillSemiBOM(strRecID);
                FillSemiLabourCost(strRecID);
            }
            else
            {
                string strSubRecID = CvtFunc.ToString(this.dgvSubSemiProduct.Rows[0].Cells["RecID"].Value);
                FillSemiBOM(strSubRecID);
                FillSemiLabourCost(strSubRecID);
            }

            this.dgvSubSemiProduct.EndEdit();
            base.SetBlankImage(this.dgvSubSemiProduct);
        }

        private bool GetCurSemiCode(ref string strRecID, ref string strSemiCode, ref string strSemiName)
        {
            if (this.tvSemi.SelectedNode == null) return false;
            string[] strSemi = tvSemi.SelectedNode.Text.ToString().Split(new string[]{"-"}, StringSplitOptions.None);
            if (strSemi.Length == 2)
            {
                strSemiCode = strSemi[0];
                strSemiName = strSemi[1];
                strRecID = CvtFunc.ToString(tvSemi.SelectedNode.Tag);
            }
            if ( CvtFunc.ToString ( mdbcon .GetValue ("select semicode from rmProductBOMSemi where recid='"+ strRecID +"'"))=="-1")
            {
                strSemiCode = "-1";
                strSemiName = tvSemi.SelectedNode.Text.ToString();
            }
            return true;
        }

     

        private void dgvSemiProduct_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dgvSemiProduct.Columns[e.ColumnIndex] is TextLookUpColumn)
            {
                if ((dgvSemiProduct.Columns[e.ColumnIndex] as TextLookUpColumn).CanLookUp())
                {
                    Dtl_LookUp(e.ColumnIndex, this.dgvSemiProduct.Name);
                }
            }
            else
            {
                if (this.dgvSemiProduct.CurrentCell.ColumnIndex == this.dgvSemiProduct.Columns["DelLine"].Index  && (this.formStatus == FormStatus.Update) && base.HasDelImage(this.dgvSemiProduct, e))
                {
                    Delete_dgvSemiProduct();
                }
            }
        }

        private void Delete_dgvSemiProduct()
        {
            if (this.dgvSemiProduct.CurrentCell != null)
            {
                this.dgvSemiProduct.CurrentCell.Selected = true;
                this.dgvSemiProduct.CurrentCell.Selected = false;
            }
            if (!this.Delete_SemiProductDetail(this.dgvSemiProduct.Rows[this.dgvSemiProduct.CurrentCell.RowIndex]))
            {
                return;
            }
            this.dgvSemiProduct.Rows.Remove(this.dgvSemiProduct.Rows[this.dgvSemiProduct.CurrentCell.RowIndex]);
            this.dgvSubSemiProduct.Rows.Clear();
            this.dgvSemiBOM.Rows.Clear();
            this.dgvSemiSubCost.Rows.Clear(); 
        }

        /// <summary>
        /// 更新 当前级 半成品 信息 dgvSemiProduct
        /// </summary>
        /// <param name="drvRow"></param>
        /// <returns></returns>
        private bool Update_SemiProductDetail(DataGridViewRow drvRow )
        {            
            string strErrMsg ="";
            this.dgvSemiProduct.EndEdit(); 
            if (CvtFunc.ToString(drvRow.Cells["SemiCode"].Value) == "-1"
                 && CvtFunc.ToString(drvRow.Cells["ParentSemiID"].Value) == "0")
            {
            }
            else
            {
                if (!CheckDtlRow_SemiProduct(ref strErrMsg))
                {
                    MsgBoxEx.Show(strErrMsg, "");
                    return false;
                }
            }
          
            DataRow drRow = mdbcon.GetDataTable("select top 0 * from rmProductBOMSemi").NewRow();
            BaseFunctions.FillDataRowByGridRow(drvRow, drRow);
            WP.RM.DataAccess.RMProductBOMHdrDAL rmDAL = new RMProductBOMHdrDAL();
            FormStatus frmStatus = new FormStatus ();
            if( CvtFunc.ToLong(  drvRow.Cells["RecID"].Value )>0)
               frmStatus = FormStatus.Update ;
            else
               frmStatus = FormStatus.AddNew ;

            bool blnReturn = rmDAL.UpdateSemiProductDetail(mdbcon, drRow, frmStatus);
            if (blnReturn)
            {
                if (CvtFunc.ToDouble(drvRow.Cells["RecID"].Value) <= 0)
                {
                    drvRow.Cells["RecID"].Value = drRow["RecID"];
                    TreeNode tvAdd = new TreeNode ();
                    tvAdd.Tag = drRow["RecID"];
                    tvAdd.Text = CvtFunc.ToString (drRow["SemiCode"]) +"-"+ CvtFunc.ToString ( drRow["SemiName"]) ;
                    this.tvSemi.SelectedNode.Nodes.Add(tvAdd);
                }
            }
            return blnReturn;
        }

        private bool Delete_dgvSemiBOM(DataGridViewRow drvRow)
        {
            if (drvRow == null) return true;
            string strSQL = "Update rmProductBOMDetail set SemiProductID=0 where RecID='{0}'";
            strSQL = string.Format(strSQL, drvRow.Cells["RecID"].Value);
            mdbcon.ExecuteSql(strSQL);
            this.dgvSemiBOM.Rows.Remove(drvRow);  
            RM.DataAccess.RMProductBOMHdrDAL rmDAL = new RMProductBOMHdrDAL();
            rmDAL.ReCalSemiProductCost(mdbcon, txtCategoryID.Text, txtProductFItemID.Text, txtSetID.Text, txtTechnicsName.Text);

            #region 
            if ( this.tvSemi.SelectedNode !=null )
            {
                tvSemi_AfterSelect(this.tvSemi, new TreeViewEventArgs(this.tvSemi.SelectedNode)); 
            }
            #endregion

            return true;
        }

        private bool Delete_dgvSemiSubCost(DataGridViewRow drvRow)
        {
            if (drvRow == null) return true;
            string strSQL = "Update rmProductBOMLabourCost set SemiProductID=0 where RecID='{0}'";
            strSQL = string.Format(strSQL, drvRow.Cells["RecID"].Value);
            mdbcon.ExecuteSql(strSQL);
            this.dgvSemiSubCost.Rows.Remove(drvRow);
            RM.DataAccess.RMProductBOMHdrDAL rmDAL = new RMProductBOMHdrDAL();
            rmDAL.ReCalSemiProductCost(mdbcon, txtCategoryID.Text, txtProductFItemID.Text, txtSetID.Text, txtTechnicsName.Text);

            #region
            if (this.tvSemi.SelectedNode != null)
            {
                tvSemi_AfterSelect(this.tvSemi, new TreeViewEventArgs(this.tvSemi.SelectedNode));
            }
            #endregion

            return true;
        }

        /// <summary>
        /// 删除当前半成品和下面的BOM 项目分摊
        /// </summary>
        /// <param name="drvRow"></param>
        /// <returns></returns>
        private bool Delete_SemiProductDetail( DataGridViewRow drvRow)
        {
            if (drvRow == null) return true ;
            string strSQL = "";
            if (MsgBoxEx.Show("您确定要删除些半成品以下级半成品？", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
            {
                string strRecID = CvtFunc.ToString(this.dgvSemiProduct.Rows[0].Cells["RecID"].Value);
                strSQL = @"with cte as
                            (
                                select RECID, SemiCode,SemiName,ParentSemiID,0 as lvl from rmProductBOMSemi
                                where recId = {0}
                                union all
                                select D.RECID,d.SemiCode,d.SemiName,D.ParentSemiID,lvl+1 from cte c inner join rmProductBOMSemi d
                                on c.recId = d.ParentSemiID
                            )
                            select * from cte where lvl>0";
                strSQL = string.Format(strSQL, strRecID);
                DataTable dtDel = mdbcon.GetDataTable(strSQL);
                foreach (DataRow drDel in dtDel.Rows)
                {
                    strSQL ="Delete from rmProductBOMSemi where RecID='"+ drDel["RecID"] +"'";
                    mdbcon.ExecuteSql(strSQL);

                    strSQL = "Update rmProductBOMLabourCost set SemiProductID=0 where SemiProductID='{0}'";
                    strSQL = string.Format(strSQL, drDel["RecID"]);
                    mdbcon.ExecuteSql(strSQL);
                    strSQL = "Update rmProductBOMDetail set SemiProductID=0 where SemiProductID='{0}'";
                    strSQL = string.Format(strSQL, drDel["RecID"]);
                    mdbcon.ExecuteSql(strSQL);
                }

                strSQL = "Delete from rmProductBOMSemi where RecID='" + strRecID + "'";
                mdbcon.ExecuteSql(strSQL);
                this.tvSemi.SelectedNode.Remove(); 
                //这里需要调用更新BOM和项目分推的过程。
                RM.DataAccess.RMProductBOMHdrDAL rmDAL = new RMProductBOMHdrDAL();
                rmDAL.ReCalSemiProductCost(mdbcon , txtCategoryID.Text , txtProductFItemID.Text , txtSetID.Text , txtTechnicsName.Text)  ;
            }            
            return true;
        }       

        private void dgvSemiProduct_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            return;
        }

        private void tvSemi_AfterSelect(object sender, TreeViewEventArgs e)
        {
            string strSemiCode = "";
            string strSemiName = "";
            string strSemiRecID = "";
            GetCurSemiCode(ref strSemiRecID , ref  strSemiCode,ref strSemiName);
            FillSemiProductGrid(strSemiRecID , strSemiCode,strSemiName);
        }

        private void InitSemiBOM()
        {
            DataGridView dgvGrid = dgvSemiBOM;
            dgvGrid.Columns.Clear();
            dgvGrid.Rows.Clear();

            DataGridViewTextBoxColumn colSeqNo = new DataGridViewTextBoxColumn();
            colSeqNo.HeaderText = "序号";
            colSeqNo.Visible = false;
            colSeqNo.Name = "SeqNo";
            colSeqNo.Width = 50;
            colSeqNo.ReadOnly = false;
            colSeqNo.SortMode = DataGridViewColumnSortMode.NotSortable;

            DataGridViewTextBoxColumn colProductFItemID = new DataGridViewTextBoxColumn();
            colProductFItemID.HeaderText = "成品编码";
            colProductFItemID.Visible = false;
            colProductFItemID.Name = "ProductFItemID";
            colProductFItemID.Width = 50;
            colProductFItemID.ReadOnly = false;
            colProductFItemID.SortMode = DataGridViewColumnSortMode.NotSortable;

            TextLookUpColumn colTechnicsName = new TextLookUpColumn();
            colTechnicsName.HeaderText = "工艺名称";
            colTechnicsName.Width = 150;
            colTechnicsName.Name = "TechnicsName";
            colTechnicsName.ReadOnly = false;
            colTechnicsName.Visible = false;
            colTechnicsName.SortMode = DataGridViewColumnSortMode.NotSortable;

            DataGridViewListColumn colCategoryID = new DataGridViewListColumn();
            colCategoryID.HeaderText = "类别编码";
            colCategoryID.Width = 80;
            colCategoryID.Name = "CategoryID";
            colCategoryID.ReadOnly = false;
            colCategoryID.Visible = false;
            colCategoryID.SortMode = DataGridViewColumnSortMode.NotSortable;

            DataGridViewListColumn colSetID = new DataGridViewListColumn();
            colSetID.HeaderText = "系列编码";
            colSetID.Width = 80;
            colSetID.Name = "SetID";
            colSetID.ReadOnly = false;
            colSetID.Visible = false;
            colSetID.SortMode = DataGridViewColumnSortMode.NotSortable;

            TextLookUpColumn colParentSemiCode = new TextLookUpColumn();
            colParentSemiCode.HeaderText = "半成品编码";
            colParentSemiCode.Width = 150;
            colParentSemiCode.Name = "ParentSemiCode";
            colParentSemiCode.ReadOnly = false;
            colParentSemiCode.Visible = false ;
            colParentSemiCode.SortMode = DataGridViewColumnSortMode.NotSortable;

            TextLookUpColumn colParentSemiID = new TextLookUpColumn();
            colParentSemiID.HeaderText = "半成品编码";
            colParentSemiID.Width = 150;
            colParentSemiID.Name = "ParentSemiID";
            colParentSemiID.ReadOnly = false;
            colParentSemiID.Visible = false;
            colParentSemiID.SortMode = DataGridViewColumnSortMode.NotSortable;

            TextLookUpColumn colParentRecID = new TextLookUpColumn();
            colParentRecID.HeaderText = "半成品编码";
            colParentRecID.Width = 150;
            colParentRecID.Name = "ParentRecID";
            colParentRecID.ReadOnly = false;
            colParentRecID.Visible = false;
            colParentRecID.SortMode = DataGridViewColumnSortMode.NotSortable;
            //WKName,ItemNo,ItemName,
            DataGridViewTextBoxColumn colWKName = new DataGridViewTextBoxColumn();
            colWKName.HeaderText = "工序名称";
            colWKName.Visible = true;
            colWKName.Width = 120;
            colWKName.Name = "WKName";
            colWKName.SortMode = DataGridViewColumnSortMode.NotSortable;

            DataGridViewTextBoxColumn colItemNo = new DataGridViewTextBoxColumn();
            colItemNo.HeaderText = "物料代码";
            colItemNo.Visible = true;
            colItemNo.Width = 80;
            colItemNo.Name = "ItemNo";
            colItemNo.SortMode = DataGridViewColumnSortMode.NotSortable;

            DataGridViewTextBoxColumn colItemName = new DataGridViewTextBoxColumn();
            colItemName.HeaderText = "物料名称";
            colItemName.Visible = true;
            colItemName.Width = 60;
            colItemName.Name = "ItemName";
            colItemName.SortMode = DataGridViewColumnSortMode.NotSortable;

            //PlanTreatCost,PriceUnit,
            DataGridViewTextBoxColumn colPlanTreatCost = new DataGridViewTextBoxColumn();
            colPlanTreatCost.HeaderText = "计划单价";
            colPlanTreatCost.Width = 70;
            colPlanTreatCost.Visible = true;
            colPlanTreatCost.Name = "PlanTreatCost";
            colPlanTreatCost.SortMode = DataGridViewColumnSortMode.NotSortable;
            colPlanTreatCost.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            colPlanTreatCost.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;

            DataGridViewTextBoxColumn colPriceUnit = new DataGridViewTextBoxColumn();
            colPriceUnit.HeaderText = "单位";
            colPriceUnit.Visible = true;
            colPriceUnit.Width = 50;
            colPriceUnit.Name = "PriceUnit";

            // Qty,DetailCost
            DataGridViewTextBoxColumn colQty = new DataGridViewTextBoxColumn();
            colQty.HeaderText = "定额数量";
            colQty.Visible = true ;
            colQty.Width = 70;
            colQty.Name = "Qty";
            colQty.SortMode = DataGridViewColumnSortMode.NotSortable;
            colQty.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            colQty.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;

            DataGridViewTextBoxColumn colDetailCost = new DataGridViewTextBoxColumn();
            colDetailCost.HeaderText = "定额成本";
            colDetailCost.Visible = true;
            colDetailCost.Width = 70;
            colDetailCost.Name = "TotPlanTreatCost";
            colDetailCost.SortMode = DataGridViewColumnSortMode.NotSortable;
            colDetailCost.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            colDetailCost.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;

            DataGridViewTextBoxColumn colRecID = new DataGridViewTextBoxColumn();
            colRecID.HeaderText = "RecID";
            colRecID.Visible = false;
            colRecID.Name = "RecID";

            DataGridViewTextBoxColumn colValueChanged = new DataGridViewTextBoxColumn();
            colValueChanged.HeaderText = "ValueChanged";
            colValueChanged.Visible = false;
            colValueChanged.Name = "ValueChanged";

            DataGridViewImageColumn colDel = new DataGridViewImageColumn();
            Bitmap delbitmap = new Bitmap(this.iglSource.Images["Del.ico"]);
            colDel.Width = 20;
            colDel.Name = "DelLine";
            colDel.HeaderText = "";
            colDel.Resizable = DataGridViewTriState.False;

            //WKName,ItemNo,ItemName,PlanTreatCost,PriceUnit,Qty,DetailCost
            dgvGrid.Columns.AddRange(new DataGridViewColumn[] { colSeqNo, colProductFItemID ,colTechnicsName,
                                                                    colCategoryID , colSetID  ,colParentRecID,colParentSemiCode, colParentSemiID ,
                                                                    colWKName, colItemNo,colItemName,
                                                                    colPlanTreatCost,colPriceUnit,colQty,colDetailCost,
                                                                    colRecID, colValueChanged, colDel });

            mDtlColumnReadOnlyArray = new bool[dgvGrid.Columns.Count];
            string[] ColumnWidthArray = DataFunctions.GetGridColumnWidthString(this.Name, this.CurrentMenuInfo.iParameter, SysVar.UserName, this.Name + "." + dgvGrid.Name).Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            for (int i = 0; i < dgvGrid.Columns.Count - 1; i++)
            {
                mDtlColumnReadOnlyArray[i] = dgvGrid.Columns[i].ReadOnly;
                if (ColumnWidthArray.Length == dgvGrid.Columns.Count) dgvGrid.Columns[i].Width = CvtFunc.ToInt(ColumnWidthArray[i]);
                dgvGrid.Columns[i].ReadOnly = true;
            }

            dgvGrid.EditMode = DataGridViewEditMode.EditOnEnter;
            dgvGrid.RowTemplate.Height = 20;
            dgvGrid.RowHeadersWidth = 23;
            dgvGrid.RowHeadersBorderStyle = DataGridViewHeaderBorderStyle.None;
            dgvGrid.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.DisableResizing;
            dgvGrid.ColumnHeadersHeight = 30;
            dgvGrid.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
            dgvGrid.SelectionMode = DataGridViewSelectionMode.CellSelect;
            dgvGrid.AllowUserToResizeRows = false;
        }
        private void FillSemiBOM(string strSemiRecID)
        {
            InitSemiBOM(); 
            int intRow =0;
            string strSQL = "Select RecID,WKName,ItemNo,ItemName,PlanTreatCost,PriceUnit,Qty,DetailCost,PlanTreatCost*Qty as TotPlanTreatCost from rmProductBOMDetail where SemiProductID='" + strSemiRecID + "'";
            DataTable dtSemiBOM = mdbcon.GetDataTable(strSQL);
            foreach (DataRow drSemiBOM in dtSemiBOM.Rows)
            {
                this.dgvSemiBOM.Rows.Add();
                this.dgvSemiBOM.Rows[intRow].Cells["RecID"].Value = drSemiBOM["RecID"];
                this.dgvSemiBOM.Rows[intRow].Cells["WKName"].Value = drSemiBOM["WKName"];
                this.dgvSemiBOM.Rows[intRow].Cells["ItemNo"].Value = drSemiBOM["ItemNo"];
                this.dgvSemiBOM.Rows[intRow].Cells["ItemName"].Value = drSemiBOM["ItemName"];
                this.dgvSemiBOM.Rows[intRow].Cells["PlanTreatCost"].Value = drSemiBOM["PlanTreatCost"];
                this.dgvSemiBOM.Rows[intRow].Cells["PriceUnit"].Value = drSemiBOM["PriceUnit"];
                this.dgvSemiBOM.Rows[intRow].Cells["Qty"].Value = drSemiBOM["Qty"];
                //this.dgvSemiBOM.Rows[intRow].Cells["DetailCost"].Value = drSemiBOM["DetailCost"];
                this.dgvSemiBOM.Rows[intRow].Cells["TotPlanTreatCost"].Value = drSemiBOM["TotPlanTreatCost"];
                intRow++;
            }
            this.dgvSemiBOM.EndEdit(); 
        }


        private void InitSemiLabourCost()
        {
            DataGridView dgvGrid = dgvSemiSubCost;
            dgvGrid.Columns.Clear();
            dgvGrid.Rows.Clear();

            DataGridViewTextBoxColumn colSeqNo = new DataGridViewTextBoxColumn();
            colSeqNo.HeaderText = "序号";
            colSeqNo.Visible = false;
            colSeqNo.Name = "SeqNo";
            colSeqNo.Width = 50;
            colSeqNo.ReadOnly = false;
            colSeqNo.SortMode = DataGridViewColumnSortMode.NotSortable;

            DataGridViewTextBoxColumn colProductFItemID = new DataGridViewTextBoxColumn();
            colProductFItemID.HeaderText = "成品编码";
            colProductFItemID.Visible = false;
            colProductFItemID.Name = "ProductFItemID";
            colProductFItemID.Width = 50;
            colProductFItemID.ReadOnly = false;
            colProductFItemID.SortMode = DataGridViewColumnSortMode.NotSortable;

            TextLookUpColumn colTechnicsName = new TextLookUpColumn();
            colTechnicsName.HeaderText = "工艺名称";
            colTechnicsName.Width = 150;
            colTechnicsName.Name = "TechnicsName";
            colTechnicsName.ReadOnly = false;
            colTechnicsName.Visible = false;
            colTechnicsName.SortMode = DataGridViewColumnSortMode.NotSortable;

            DataGridViewListColumn colCategoryID = new DataGridViewListColumn();
            colCategoryID.HeaderText = "类别编码";
            colCategoryID.Width = 80;
            colCategoryID.Name = "CategoryID";
            colCategoryID.ReadOnly = false;
            colCategoryID.Visible = false;
            colCategoryID.SortMode = DataGridViewColumnSortMode.NotSortable;

            DataGridViewListColumn colSetID = new DataGridViewListColumn();
            colSetID.HeaderText = "系列编码";
            colSetID.Width = 80;
            colSetID.Name = "SetID";
            colSetID.ReadOnly = false;
            colSetID.Visible = false;
            colSetID.SortMode = DataGridViewColumnSortMode.NotSortable;

            TextLookUpColumn colParentSemiCode = new TextLookUpColumn();
            colParentSemiCode.HeaderText = "半成品编码";
            colParentSemiCode.Width = 150;
            colParentSemiCode.Name = "ParentSemiCode";
            colParentSemiCode.ReadOnly = false;
            colParentSemiCode.Visible = false ;
            colParentSemiCode.SortMode = DataGridViewColumnSortMode.NotSortable;

            TextLookUpColumn colParentSemiID = new TextLookUpColumn();
            colParentSemiID.HeaderText = "半成品编码ID";
            colParentSemiID.Width = 150;
            colParentSemiID.Name = "ParentSemiID";
            colParentSemiID.ReadOnly = false;
            colParentSemiID.Visible = false;
            colParentSemiID.SortMode = DataGridViewColumnSortMode.NotSortable;

            TextLookUpColumn colParentRecID = new TextLookUpColumn();
            colParentRecID.HeaderText = "半成品编码RecID";
            colParentRecID.Width = 150;
            colParentRecID.Name = "ParentRecID";
            colParentRecID.ReadOnly = false;
            colParentRecID.Visible = false;
            colParentRecID.SortMode = DataGridViewColumnSortMode.NotSortable;
            //WKName,TotalQty,StandardQty
            DataGridViewTextBoxColumn colWKName = new DataGridViewTextBoxColumn();
            colWKName.HeaderText = "工序名称";
            colWKName.Visible = true;
            colWKName.Width = 120;
            colWKName.Name = "WKName";
            colWKName.SortMode = DataGridViewColumnSortMode.NotSortable;

            DataGridViewTextBoxColumn colTotalQty = new DataGridViewTextBoxColumn();
            colTotalQty.HeaderText = "计量数量";
            colTotalQty.Visible = true;
            colTotalQty.Width = 80;
            colTotalQty.Name = "TotalQty";
            colTotalQty.SortMode = DataGridViewColumnSortMode.NotSortable;
            colTotalQty.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;
            colTotalQty.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;

            DataGridViewTextBoxColumn colStandardQty = new DataGridViewTextBoxColumn();
            colStandardQty.HeaderText = "额定数量";
            colStandardQty.Visible = true;
            colStandardQty.Width = 60;
            colStandardQty.Name = "StandardQty";
            colStandardQty.SortMode = DataGridViewColumnSortMode.NotSortable;

            //SpendHours,StandardWage,
            DataGridViewTextBoxColumn colSpendHours = new DataGridViewTextBoxColumn();
            colSpendHours.HeaderText = "耗用工时";
            colSpendHours.Width = 70;
            colSpendHours.Visible = true;
            colSpendHours.Name = "SpendHours";
            colSpendHours.SortMode = DataGridViewColumnSortMode.NotSortable;
            colSpendHours.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            colSpendHours.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;

            DataGridViewTextBoxColumn colStandardWage = new DataGridViewTextBoxColumn();
            colStandardWage.HeaderText = "固定工资";
            colStandardWage.Visible = true;
            colStandardWage.Width = 50;
            colStandardWage.Name = "StandardWage";
            colStandardWage.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;
            colStandardWage.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;

            // StandardWage26,UnitCost
            DataGridViewTextBoxColumn colStandardWage26 = new DataGridViewTextBoxColumn();
            colStandardWage26.HeaderText = "标准工资";
            colStandardWage26.Visible = false;
            colStandardWage26.Width = 70;
            colStandardWage26.Name = "StandardWage26";
            colStandardWage26.SortMode = DataGridViewColumnSortMode.NotSortable;
            colStandardWage26.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            colStandardWage26.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;

            DataGridViewTextBoxColumn colUnitCost = new DataGridViewTextBoxColumn();
            colUnitCost.HeaderText = "计件工价";
            colUnitCost.Visible = true;
            colUnitCost.Width = 70;
            colUnitCost.Name = "UnitCost";
            colUnitCost.SortMode = DataGridViewColumnSortMode.NotSortable;
            colUnitCost.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            colUnitCost.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;
            
            //TotUnitCost,DetailCost, 
            DataGridViewTextBoxColumn colTotUnitCost = new DataGridViewTextBoxColumn();
            colTotUnitCost.HeaderText = "计件工资";
            colTotUnitCost.Visible = false;
            colTotUnitCost.Width = 70;
            colTotUnitCost.Name = "TotUnitCost";
            colTotUnitCost.SortMode = DataGridViewColumnSortMode.NotSortable;
            colTotUnitCost.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;
            colTotUnitCost.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;

            DataGridViewTextBoxColumn colDetailCost = new DataGridViewTextBoxColumn();
            colDetailCost.HeaderText = "人工成本";
            colDetailCost.Visible = false;
            colDetailCost.Width = 70;
            colDetailCost.Name = "DetailCost";
            colDetailCost.SortMode = DataGridViewColumnSortMode.NotSortable;
            colDetailCost.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;
            colDetailCost.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            //WorkCost, DetailTotWorkCost
            DataGridViewTextBoxColumn colWorkCost = new DataGridViewTextBoxColumn();
            colWorkCost.HeaderText = "工时费用标准";
            colWorkCost.Visible = true;
            colWorkCost.Width = 80;
            colWorkCost.Name = "WorkCost";
            colWorkCost.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            colWorkCost.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;
            colWorkCost.SortMode = DataGridViewColumnSortMode.NotSortable;

            DataGridViewTextBoxColumn colDetailTotWorkCost = new DataGridViewTextBoxColumn();
            colDetailTotWorkCost.HeaderText = "工时费用标准";
            colDetailTotWorkCost.Visible = true;
            colDetailTotWorkCost.Width = 80;
            colDetailTotWorkCost.Name = "DetailTotWorkCost";
            colDetailTotWorkCost.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            colDetailTotWorkCost.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;
            colDetailTotWorkCost.SortMode = DataGridViewColumnSortMode.NotSortable;
            
            DataGridViewTextBoxColumn colRecID = new DataGridViewTextBoxColumn();
            colRecID.HeaderText = "RecID";
            colRecID.Visible = false;
            colRecID.Name = "RecID";

            DataGridViewTextBoxColumn colValueChanged = new DataGridViewTextBoxColumn();
            colValueChanged.HeaderText = "ValueChanged";
            colValueChanged.Visible = false;
            colValueChanged.Name = "ValueChanged";

            DataGridViewImageColumn colDel = new DataGridViewImageColumn();
            Bitmap delbitmap = new Bitmap(this.iglSource.Images["del.ico"]);
            colDel.Width = 20;
            colDel.Name = "DelLine";
            colDel.HeaderText = "";
            colDel.Resizable = DataGridViewTriState.False;

            //TotalQty,StandardQty, SpendHours,StandardWage,StandardWage26,UnitCost,TotUnitCost,DetailCost, WorkCost, DetailTotWorkCost
            dgvGrid.Columns.AddRange(new DataGridViewColumn[] { colSeqNo, colProductFItemID ,colTechnicsName,
                                                                    colCategoryID , colSetID  ,colParentRecID,colParentSemiCode, colParentSemiID ,
                                                                    colWKName, colTotalQty,colStandardQty,
                                                                    colSpendHours,colStandardWage,colStandardWage26,colUnitCost, colTotUnitCost,
                                                                    colDetailCost,colWorkCost,colDetailTotWorkCost,
                                                                    colRecID, colValueChanged, colDel });

            mDtlColumnReadOnlyArray = new bool[dgvGrid.Columns.Count];
            string[] ColumnWidthArray = DataFunctions.GetGridColumnWidthString(this.Name, this.CurrentMenuInfo.iParameter, SysVar.UserName, this.Name + "." + dgvGrid.Name).Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            for (int i = 0; i < dgvSemiProduct.Columns.Count; i++)
            {
                mDtlColumnReadOnlyArray[i] = dgvGrid.Columns[i].ReadOnly;
                if (ColumnWidthArray.Length == dgvGrid.Columns.Count) dgvGrid.Columns[i].Width = CvtFunc.ToInt(ColumnWidthArray[i]);
                dgvGrid.Columns[i].ReadOnly = true;
            }

            dgvGrid.EditMode = DataGridViewEditMode.EditOnEnter;
            dgvGrid.RowTemplate.Height = 20;
            dgvGrid.RowHeadersWidth = 23;
            dgvGrid.RowHeadersBorderStyle = DataGridViewHeaderBorderStyle.None;
            dgvGrid.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.DisableResizing;
            dgvGrid.ColumnHeadersHeight = 30;
            dgvGrid.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
            dgvGrid.SelectionMode = DataGridViewSelectionMode.CellSelect;
            dgvGrid.AllowUserToResizeRows = false;
        }
        private void FillSemiLabourCost(string strSemiRecID)
        {
            int intRow = 0;
            InitSemiLabourCost();
            string strSQL = @"Select RecID,WKName,TotalQty,StandardQty, SpendHours,StandardWage,StandardWage26,
                              UnitCost,TotUnitCost,DetailCost, WorkCost, DetailTotWorkCost from rmProductBOMLabourCost 
                              where SemiProductID='" + strSemiRecID + "'";
            DataTable dtSemiLabourCost = mdbcon.GetDataTable(strSQL);
            foreach (DataRow drSemiLabourCost in dtSemiLabourCost.Rows)
            {
                this.dgvSemiSubCost.Rows.Add();
                this.dgvSemiSubCost.Rows[intRow].Cells["RecID"].Value = drSemiLabourCost["RecID"];
                this.dgvSemiSubCost.Rows[intRow].Cells["WKName"].Value = drSemiLabourCost["WKName"];
                this.dgvSemiSubCost.Rows[intRow].Cells["TotalQty"].Value = drSemiLabourCost["TotalQty"];
                this.dgvSemiSubCost.Rows[intRow].Cells["StandardQty"].Value = drSemiLabourCost["StandardQty"];
                this.dgvSemiSubCost.Rows[intRow].Cells["SpendHours"].Value = drSemiLabourCost["SpendHours"];
                this.dgvSemiSubCost.Rows[intRow].Cells["StandardWage"].Value = drSemiLabourCost["StandardWage"];
                this.dgvSemiSubCost.Rows[intRow].Cells["StandardWage26"].Value = drSemiLabourCost["StandardWage26"];
                this.dgvSemiSubCost.Rows[intRow].Cells["UnitCost"].Value = drSemiLabourCost["UnitCost"];
                this.dgvSemiSubCost.Rows[intRow].Cells["TotUnitCost"].Value = drSemiLabourCost["TotUnitCost"];
                this.dgvSemiSubCost.Rows[intRow].Cells["DetailCost"].Value = drSemiLabourCost["DetailCost"];
                this.dgvSemiSubCost.Rows[intRow].Cells["WorkCost"].Value = drSemiLabourCost["WorkCost"];
                this.dgvSemiSubCost.Rows[intRow].Cells["DetailTotWorkCost"].Value = drSemiLabourCost["DetailTotWorkCost"];
                intRow++;
            }
            base.SetBlankImage(this.dgvSemiSubCost);
        }
    

        private void dgvSemiBOM_RowEnter(object sender, DataGridViewCellEventArgs e)
        {
            base.SetGridViewDelImage(this.dgvSemiBOM, e, this.dgvSemiBOM.Columns.Count - 1);
            if (e.RowIndex > 0)
            {
                string strSemiRecID = CvtFunc.ToString (this.dgvSemiBOM.Rows[e.RowIndex].Cells["RecID"].Value);
                //FillSemiBOM(strSemiRecID);
                //FillSemiLabourCost(strSemiRecID);  
            }
        }

        private void dgvSemiBOM_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dgvSemiBOM.Columns[e.ColumnIndex] is TextLookUpColumn)
            {
                if ((dgvSemiBOM.Columns[e.ColumnIndex] as TextLookUpColumn).CanLookUp())
                {
                    Dtl_LookUp(e.ColumnIndex, this.dgvSemiBOM.Name);
                }
            }
            else
            {
                if (this.dgvSemiBOM.CurrentCell.ColumnIndex == this.dgvSemiBOM.Columns["DelLine"].Index && (this.formStatus == FormStatus.Update) && base.HasDelImage(this.dgvSemiBOM, e))
                {
                    Delete_dgvSemiBOM(this.dgvSemiBOM.CurrentRow);
                }
            }
        }

        private void BtnSelBOMToSemiProduct_Click(object sender, EventArgs e)
        {
            if (this.tvSemi.SelectedNode == null) return;
            if (this.tvSemi.SelectedNode.Nodes.Count > 0)
            {
                MsgBoxEx.Show("只能为最后一级添加BOM明细", "");
                return;
            }
            
            string strRecID = CvtFunc.ToString(this.tvSemi.SelectedNode.Tag);
            
            frmRMCopyToSemiProduct frmLabourCost = new frmRMCopyToSemiProduct();
            frmRMCopyToSemiProduct.Parameter para = new frmRMCopyToSemiProduct.Parameter();
            para.strSemiProductID = strRecID ;
            frmLabourCost.ShowFrom(frmRMCopyToSemiProduct.FromType.BOM, this.dgvBOM, para);
            if (frmLabourCost.mblnHasReturn)
            {
                foreach (DataGridViewRow dgvRow in frmLabourCost.dgvBOM.Rows)
                {
                    if (CvtFunc.ToBoolean(dgvRow.Cells["SEL"].Value))
                    {
                        string strSQL = "Update rmProductBOMDetail Set SemiProductID='{0}' Where RecID='{1}'";
                        strSQL = string.Format(strSQL, strRecID, CvtFunc.ToString(dgvRow.Cells["RecID"].Value));
                        mdbcon.ExecuteSql(strSQL);
                    }
                }
                RMProductBOMHdrDAL rmDAL = new RMProductBOMHdrDAL();
                rmDAL.CalSemiProductCost(mdbcon, strRecID);
                string strSemiCode = "", strSemiName = "",strSemiRecID="";
                GetCurSemiCode(ref strSemiRecID, ref strSemiCode, ref strSemiName);  
                FillSemiProductGrid(strSemiRecID , strSemiCode ,strSemiName); 
            }
        }

        private void BtnSelLabourCostToSemiProduct_Click(object sender, EventArgs e)
        {
            if (this.tvSemi.SelectedNode == null) return;
            if (this.tvSemi.SelectedNode.Nodes.Count > 0)
            {
                MsgBoxEx.Show("只能为最后一级添加项目分推明细", "");
                return;
            }
            
            string strRecID = CvtFunc.ToString(this.tvSemi.SelectedNode.Tag);

            frmRMCopyToSemiProduct frmLabourCost = new frmRMCopyToSemiProduct();
            frmRMCopyToSemiProduct.Parameter para = new frmRMCopyToSemiProduct.Parameter();
            para.strSemiProductID = strRecID;
            frmLabourCost.ShowFrom(frmRMCopyToSemiProduct.FromType.LabourCost, this.dgvLabourCost, para);
            if (frmLabourCost.mblnHasReturn)
            {
                foreach (DataGridViewRow dgvRow in frmLabourCost.dgvBOM.Rows)
                {
                    if (CvtFunc.ToBoolean(dgvRow.Cells["SEL"].Value))
                    {
                        string strSQL = "Update rmProductBOMLabourCost Set SemiProductID='{0}' Where RecID='{1}'";
                        strSQL = string.Format(strSQL, strRecID, CvtFunc.ToString(dgvRow.Cells["RecID"].Value ));
                        mdbcon.ExecuteSql(strSQL);
                    }
                }
                //需要写更新半成品的BOM和LabourCost
                RMProductBOMHdrDAL rmDAL = new RMProductBOMHdrDAL();
                rmDAL.CalSemiProductCost(mdbcon, strRecID);
                
                string strSemiCode = "", strSemiName = "", strSemiRecID = "";
                GetCurSemiCode(ref strSemiRecID, ref strSemiCode, ref strSemiName);
                rmDAL.ReCalSemiProductCost(mdbcon, txtCategoryID.Text, txtProductFItemID.Text, txtSetID.Text, txtTechnicsName.Text); 
                FillSemiProductGrid(strSemiRecID, strSemiCode, strSemiName);                
            }
        }

        private void BtnDelSemiProduct_Click(object sender, EventArgs e)
        {
            Delete_dgvSemiProduct();
        }

        private void btnSaveSemiProduct_Click(object sender, EventArgs e)
        {
            Update_SemiProductDetail(this.dgvSemiProduct.CurrentRow);  
        }

        private void btnAddSemiProduct_Click(object sender, EventArgs e)
        {
            if (this.tvSemi.SelectedNode == null) return;
            
            string strParentRecID = CvtFunc.ToString(this.tvSemi.SelectedNode.Tag);
            string strSemiCode = "";
            string strSemiName = "";
            string strSemiRecID = "";
            GetCurSemiCode(ref strSemiRecID,ref strSemiCode,ref  strSemiName);


            if ( CvtFunc.ToInt(mdbcon.GetValue("select count(*) from rmProductBOMDetail where semiproductid='"+ strParentRecID +"'"))>0)
            {
                MsgBoxEx.Show("不能为此级半成品添加下级半成品。", "");
                return;
            }

            if (CvtFunc.ToInt(mdbcon.GetValue("select count(*) from rmProductBOMLabourCost where semiproductid='" + strParentRecID + "'")) > 0)
            {
                MsgBoxEx.Show("不能为此级半成品添加下级半成品。", "");
                return;
            }

            this.dgvSemiProduct.Rows.Clear();
            this.dgvSemiProduct.Rows.Add();

            this.dgvSubSemiProduct.Rows.Clear();
            this.dgvSemiBOM.Rows.Clear();
            this.dgvSemiSubCost.Rows.Clear();

            this.dgvSemiProduct.Rows[0].Cells["RecID"].Value = "0";
            this.dgvSemiProduct.Rows[0].Cells["ParentRecID"].Value = strParentRecID ;
            this.dgvSemiProduct.Rows[0].Cells["semicode"].Value = "";
            this.dgvSemiProduct.Rows[0].Cells["seminame"].Value = "";
            this.dgvSemiProduct.Rows[0].Cells["ParentSemiID"].Value = strParentRecID;
            this.dgvSemiProduct.Rows[0].Cells["ParentSemiCode"].Value = strSemiCode  ;
            this.dgvSemiProduct.Rows[0].Cells["CategoryID"].Value = txtCategoryID.Text ;
            this.dgvSemiProduct.Rows[0].Cells["SetID"].Value = txtSetID.Text  ;
            this.dgvSemiProduct.Rows[0].Cells["ProductFItemID"].Value = txtProductFItemID.Text  ;
            this.dgvSemiProduct.Rows[0].Cells["TechnicsName"].Value = txtTechnicsName.Text ;
            this.dgvSemiProduct.Rows[0].Cells["Quantity"].Value = "0";
            this.dgvSemiProduct.Rows[0].Cells["Unit"].Value ="";
            this.dgvSemiProduct.Rows[0].Cells["WastageRate"].Value = "0";
            this.dgvSemiProduct.Rows[0].Cells["WorkCost"].Value = "0";
            this.dgvSemiProduct.Rows[0].Cells["LabourCost"].Value = "0";
            this.dgvSemiProduct.Rows[0].Cells["BOMCost"].Value = "0";
            this.dgvSemiProduct.Rows[0].Cells["SemiTotalCost"].Value = "0";

            this.dgvSemiProduct.EndEdit(); 
        }

        private bool CheckDtlRow_SemiProduct(ref string strErrMsg)
        {
            bool bCheckResult = true;
            for (int i = 0; i < dgvSemiProduct.ColumnCount - 1; i++)
            {
                bCheckResult = CheckDtlCell_SemiProduct(i, ref strErrMsg);
                if (!bCheckResult) break;
            }
            return bCheckResult;
        }
        private bool CheckDtlCell_SemiProduct(int iColumn, ref string strErrMsg)
        {
            bool bReturnValue = true;
            strErrMsg = "";
            string strValue = "";
            if (this.dgvSemiProduct.CurrentRow != null && this.dgvSemiProduct.CurrentRow.Cells[iColumn].Value != null)
            {
                strValue = this.dgvSemiProduct.CurrentRow.Cells[iColumn].Value.ToString().TrimEnd();
            }

            if (iColumn == CvtFunc.ToInt(this.dgvSemiProduct.Columns["SemiCode"].Index ))
            {
                if (strValue == "")
                {
                    strErrMsg = "代码不能为空.";
                    return false;
                }
                else if (!DataFunctions.CheckRecordExist(mdbcon, "imSemiProduct", strValue, "SemiCode") )
                {
                    strErrMsg = "代码不存在.";
                    return false;
                }
            }
            else if (iColumn == CvtFunc.ToInt(this.dgvSemiProduct.Columns["SemiName"].Index))
            {
                if (strValue == "")
                {
                    strErrMsg = "代码名称不能为空.";
                    return false;
                }              
            }
            else if (iColumn == CvtFunc.ToInt(this.dgvSemiProduct.Columns["Unit"].Index))
            {
                if (strValue == "")
                {
                    strErrMsg = "单位不能为空.";
                    return false;
                }
            }
            return bReturnValue;
        }
        #endregion

        private void dgvSemiProduct_RowEnter(object sender, DataGridViewCellEventArgs e)
        {
            base.SetGridViewDelImage(this.dgvSemiProduct, e, this.dgvSemiProduct.Columns.Count -1);
        }

        private void dgvSubSemiProduct_RowEnter(object sender, DataGridViewCellEventArgs e)
        {
            base.SetGridViewDelImage(this.dgvSubSemiProduct, e, this.dgvSubSemiProduct.Columns.Count - 1);

            if (CvtFunc.ToInt(this.dgvSubSemiProduct.Rows[e.RowIndex].Cells["RecID"].Value)>0)
            {
                string strSubRecID = CvtFunc.ToString(this.dgvSubSemiProduct.Rows[e.RowIndex].Cells["RecID"].Value);
                FillSemiBOM(strSubRecID);
                FillSemiLabourCost(strSubRecID);
            }
        }

        private void tvSemi_MouseDown(object sender, MouseEventArgs e)
        {
        }

        private void dgvSemiSubCost_RowEnter(object sender, DataGridViewCellEventArgs e)
        {
            base.SetGridViewDelImage(this.dgvSemiSubCost, e, this.dgvSemiSubCost.Columns.Count - 1);
        }

        private void btnApprovalHistory_Click(object sender, EventArgs e)
        {
            string strRecID = this.RecID.ToString();
            frmApprovalHistory frmHist = new frmApprovalHistory(mdbcon, frmApprovalHistory.TableType.ProductBOM, strRecID);
            frmHist.Text = "审核历史记录";
            frmHist.ShowDialog(); 
        }

        private void dgvSemiSubCost_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            return;
        }
        private void dgvSemiProduct_CellEnter(object sender, DataGridViewCellEventArgs e)
        {
            if (this.dgvSemiProduct.CurrentRow == null) return;
            if (CvtFunc.ToString(this.dgvSemiProduct.Rows[e.RowIndex].Cells["SemiCode"].Value) == "-1"
                 && CvtFunc.ToString(this.dgvSemiProduct.Rows[e.RowIndex].Cells["ParentSemiID"].Value) == "0")
            {
                this.dgvSemiProduct.CurrentCell.ReadOnly = true;
            }
        }
        
        private void dgvSemiSubCost_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dgvSemiSubCost.Columns[e.ColumnIndex] is TextLookUpColumn)
            {
                if ((dgvSemiSubCost.Columns[e.ColumnIndex] as TextLookUpColumn).CanLookUp())
                {
                    Dtl_LookUp(e.ColumnIndex, this.dgvSemiSubCost.Name);
                }
            }
            else
            {
                if (this.dgvSemiSubCost.CurrentCell.ColumnIndex == this.dgvSemiSubCost.Columns["DelLine"].Index && (this.formStatus == FormStatus.Update) && base.HasDelImage(this.dgvSemiSubCost, e))
                {
                    Delete_dgvSemiSubCost(this.dgvSemiSubCost.CurrentRow);
                }
            }
        }

        private void dgvSemiProduct_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (m_bCanTrigerCellValueChangedEven_SemiProduct)
            {
                if (e.ColumnIndex == this.dgvSemiProduct.Columns["WastageRate"].Index)
                {
                    this.Update_SemiProductDetail(this.dgvSemiProduct.CurrentRow);
                    string strSemiCode = "";
                    string strSemiName = "";
                    string strSemiRecID = "";
                    GetCurSemiCode(ref strSemiRecID, ref  strSemiCode, ref strSemiName);
                    FillSemiProductGrid(strSemiRecID, strSemiCode, strSemiName);
                }
            }
        }

     
      

     
    }
}
